Java 为什么我们需要decorator模式中的抽象decorator类?
在Java 为什么我们需要decorator模式中的抽象decorator类?,java,scala,design-patterns,decorator,Java,Scala,Design Patterns,Decorator,在装饰器模式中,如果 删除decorators继承并删除的抽象decorator类 使装饰器直接继承装饰对象的接口 输出是相同的 我的问题是,为什么还要添加额外的抽象类来制作装饰器呢 例如: 标准decorator模式的Scala源代码如下: 而遵循上述步骤的我的版本如下: (通过删除抽象decorator类(CoffeeDecorator此处),并让decorator直接继承被装饰者(Coffee此处)) 在闲逛之后,我发现了区别。 抽象装饰器提供了默认的重写,因此在某些情况下,装饰器实现的
装饰器模式中
,如果
抽象类来制作装饰器呢
例如:
标准decorator模式的Scala
源代码如下:
而遵循上述步骤的我的版本如下:
(通过删除抽象decorator类(CoffeeDecorator
此处),并让decorator直接继承被装饰者(Coffee
此处))
在闲逛之后,我发现了区别。
抽象装饰器提供了默认的重写,因此在某些情况下,装饰器实现的类型更少,因为我们并不总是装饰所有的方法并提供公共的帮助程序
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"
}
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"
}