为什么我们需要装饰器模式中的抽象装饰器类?

时间:2018-08-11 11:03:22

标签: java scala design-patterns decorator

Decorator Pattern中,如果我

  1. 删除抽象装饰器类,该装饰器是继承的,并且
  2. 具有装饰器直接继承 decoratee 的界面。

输出是相同的。

我的问题是,为什么要麻烦添加额外的abstractor class来制作装饰器?


例如:

标准Scala的{​​{1}}源代码在这里:https://gist.github.com/kencoba/1875983

我的版本遵循上述步骤时,如下所示: (通过删除抽象装饰器类(此处为decorator pattern),并使装饰器直接继承被装饰者(此处为CoffeeDecorator))

Coffee

1 个答案:

答案 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"
}