当我使用Java(或类似语言)进行编程时,我经常使用简单版本的策略模式,使用接口和实现类,在我的代码中提供特定概念的运行时可选实现。
作为一个非常人为的例子,我可能希望拥有一个可以在我的Java代码中产生噪音的动物的一般概念,并希望能够在运行时选择动物的类型。所以我会按照这些方式编写代码:
interface Animal {
void makeNoise();
}
class Cat extends Animal {
void makeNoise() { System.out.println("Meow"); }
}
class Dog extends Animal {
void makeNoise() { System.out.println("Woof"); }
}
class AnimalContainer {
Animal myAnimal;
AnimalContainer(String whichOne) {
if (whichOne.equals("Cat"))
myAnimal = new Cat();
else
myAnimal = new Dog();
}
void doAnimalStuff() {
...
// Time for the animal to make a noise
myAnimal.makeNoise();
...
}
足够简单。不过,最近,我一直在Scala开展一个项目,我想做同样的事情。使用特征这样做似乎很容易,例如:
trait Animal {
def makeNoise:Unit
}
class Cat extends Animal {
override def makeNoise:Unit = println("Meow")
}
class AnimalContainer {
val myAnimal:Animal = new Cat
...
}
然而,这看起来非常类似Java而且不是很实用 - 更不用说特征和接口不是真的同样的东西。所以我想知道在我的Scala代码中是否有更惯用的方法来实现策略模式 - 或类似的东西 - 以便我可以在运行时选择抽象概念的具体实现。或者使用特征是实现这一目标的最佳方式?
答案 0 :(得分:11)
它可能就像“Design pattern in scala”中的那个例子:
就像任何函数是一流对象或闭包可用的语言一样,策略模式是显而易见的 例如。考虑“征税”的例子:
trait TaxPayer
case class Employee(sal: Long) extends TaxPayer
case class NonProfitOrg(funds: BigInt) extends TaxPayer
//Consider a generic tax calculation function. (It can be in TaxPayer also).
def calculateTax[T <: TaxPayer](victim: T, taxingStrategy: (T => long)) = {
taxingStrategy(victim)
}
val employee = new Employee(1000)
//A strategy to calculate tax for employees
def empStrategy(e: Employee) = Math.ceil(e.sal * .3) toLong
calculateTax(employee, empStrategy)
val npo = new NonProfitOrg(100000000)
//The tax calculation strategy for npo is trivial, so we can inline it
calculateTax(nonProfit, ((t: TaxPayer) => 0)
这样我就可以在运行时选择抽象概念的具体实现。
您正在使用 upper bound ,以便将子类中T的特化限制为TaxPayer
的子类型。
答案 1 :(得分:8)
您可以对蛋糕模式进行修改。
trait Animal {
def makenoise: Unit
}
trait Cat extends Animal {
override def makeNoise { println("Meow") }
}
trait Dog extends Animal {
override def makeNoise { println("Woof") }
}
class AnimalContaineer {
self: Animal =>
def doAnimalStuff {
// ...
makeNoise
// ...
}
}
object StrategyExample extends Application {
val ex1 = new AnimalContainer with Dog
val ex2 = new AnimalContainer with Cat
ex1.doAnimalStuff
ex2.doAnimalStuff
}
就策略模式而言,策略中的自我类型表明它必须与某种算法的特定实现混合。
答案 2 :(得分:3)
来自Java,我仍然喜欢OO样式语法。我也只是观看了Deriving Scalaz的第一部分(免责声明),并将其作为一个小练习向我自己展示了Pimp My Library和Implicits的概念。我想我也可以分享我的发现。一般来说,以这种方式进行设置会产生更多的编程开销,但我个人认为用法更清晰。
第一个片段演示了如何添加Pimp My Library模式。
trait TaxPayer
/**
* This is part of the Pimp My Library pattern which converts any subclass of
* TaxPayer to type TaxPayerPimp
*/
object TaxPayer {
implicit def toTaxPayerPimp[T <: TaxPayer](t: T) : TaxPayerPimp[T] =
new TaxPayerPimp[T] {
val taxPayer = t
}
}
/**
* This is an extra trait defining tax calculation which will be overloaded by
* individual TaxCalculator strategies.
*/
trait TaxCalculator[T <: TaxPayer] {
def calculate(t: T) : Long
}
/**
* This is the other part of the Pimp My Library pattern and is analogus to
* Scalaz's Identity trait.
*/
trait TaxPayerPimp[T <: TaxPayer] {
val taxPayer: T
def calculateTax(tc: TaxCalculator[T]) : Long = tc.calculate(taxPayer)
}
case class Employee(sal: Long) extends TaxPayer
/**
* This is the employee companion object which defines the TaxCalculator
* strategies.
*/
object Employee {
object DefaultTaxCalculator extends TaxCalculator[Employee] {
def calculate(e: Employee) = Math.ceil(e.sal * .3) toLong
}
object BelgianTaxCalculator extends TaxCalculator[Employee] {
def calculate(e: Employee) = Math.ceil(e.sal * .5) toLong
}
}
case class NonProfitOrg(funds: BigInt) extends TaxPayer
/**
* This is the NonProfitOrg companion which defines it's own TaxCalculator
* strategies.
*/
object NonProfitOrg {
object DefaultTaxCalculator extends TaxCalculator[NonProfitOrg] {
def calculate(n: NonProfitOrg) = 0
}
}
object TaxPayerMain extends Application {
//The result is a more OO style version of VonC's example
val employee = new Employee(1000)
employee.calculateTax(Employee.DefaultTaxCalculator)
employee.calculateTax(Employee.BelgianTaxCalculator)
val npo = new NonProfitOrg(100000000)
npo.calculateTax(NonProfitOrg.DefaultTaxCalculator)
//Note the type saftey, this will not compile
npo.calculateTax(Employee.DefaultTaxCalculator)
}
我们可以使用implicits进一步了解这一点。
trait TaxPayer
object TaxPayer {
implicit def toTaxPayerPimp[T <: TaxPayer](t: T) : TaxPayerPimp[T] =
new TaxPayerPimp[T] {
val taxPayer = t
}
}
trait TaxCalculator[T <: TaxPayer] {
def calculate(t: T) : Long
}
/**
* Here we've added an implicit to the calculateTax function which tells the
* compiler to look for an implicit TaxCalculator in scope.
*/
trait TaxPayerPimp[T <: TaxPayer] {
val taxPayer: T
def calculateTax(implicit tc: TaxCalculator[T]) : Long = tc.calculate(taxPayer)
}
case class Employee(sal: Long) extends TaxPayer
/**
* Here we've added implicit to the DefaultTaxCalculator. If in scope
* and the right type, it will be implicitely used as the parameter in the
* TaxPayerPimp.calculateTax function.
*
*
*/
object Employee {
implicit object DefaultTaxCalculator extends TaxCalculator[Employee] {
def calculate(e: Employee) = Math.ceil(e.sal * .3) toLong
}
object BelgianTaxCalculator extends TaxCalculator[Employee] {
def calculate(e: Employee) = Math.ceil(e.sal * .5) toLong
}
}
/**
* Added implicit to the DefaultTaxCalculator...
*/
case class NonProfitOrg(funds: BigInt) extends TaxPayer
object NonProfitOrg {
implicit object DefaultTaxCalculator extends TaxCalculator[NonProfitOrg] {
def calculate(n: NonProfitOrg) = 0
}
}
object TaxPayer2 extends Application {
println("TaxPayer2")
val taxPayer = new Employee(1000)
//Now the call to calculateTax will
//implicitely use Employee.DefaultTaxCalculator
taxPayer.calculateTax
//But if we want, we can still explicitely pass in the BelgianTaxCalculator
taxPayer.calculateTax(Employee.BelgianTaxCalculator)
val npo = new NonProfitOrg(100000000)
//implicitely uses NonProfitOrg.defaultCalculator
npo.calculateTax
}