在Decorator Pattern
中,如果我
输出是相同的。
我的问题是,为什么要麻烦添加额外的abstractor class
来制作装饰器?
例如:
标准Scala
的{{1}}源代码在这里:https://gist.github.com/kencoba/1875983
我的版本遵循上述步骤时,如下所示:
(通过删除抽象装饰器类(此处为decorator pattern
),并使装饰器直接继承被装饰者(此处为CoffeeDecorator
))
Coffee
答案 0 :(得分:1)
摆弄之后,我发现了区别。 该抽象装饰器提供了默认的重写,因此在某些情况下,由于我们并不总是装饰所有方法并提供公共帮助器,因此使装饰器实现的类型更少。
trait Coffee {
def cost: Double
def ingredients: String
}
class FreeMilk(decoratedCoffee: Coffee) extends Coffee {
// this is a waste of line
override def cost = decoratedCoffee.cost
override def ingredients = decoratedCoffee.ingredients + "," + "Milk"
}
abstract class CoffeeDecorator(decoratedCoffee: Coffee) extends Coffee {
val sep = ", "
override def cost = decoratedCoffee.cost
override def ingredients = decoratedCoffee.ingredients
}
class FreeMilk2(decoratedCoffee: Coffee) extends CoffeeDecorator(decoratedCoffee) {
// less typings and give you some base helpers
override def ingredients = super.ingredients + sep + "Milk"
}