装饰模式:动态给一个对象添加一些额外的职责
,就像在墙上刷油漆,使用装饰模式相比生成子类达到的功能更加灵活
【场景】使用继承来实现功能的扩展,如果扩展的功能种类繁多,那么势必生成很多子类
【要点】装饰着与被装饰者拥有共同的超类,,继承的目的是继承类型,而不是行为
扩展体现在继承、修改体现在子类中,而不是具体的抽象类,这充分体现了依赖倒置原则,这是自己理解的装饰者模式
我们一Coffee为例子,去喝Coffee的时候往往有很多口味,原味,加牛奶,加糖的,这时候价格也不一样,但是主要的还是Coffee,其他的只是佐料,由此我们感觉到了,装饰只是扩展了外形,而本质不能变
protocol
Coffe{
func getCost()-> Double
func getIngredients()-> String
}
class SimpleCoffe: Coffe {
func getCost() -> Double {
return 1.0
}
func getIngredients() -> String {
return "Coffe"
}
func getCost()-> Double
func getIngredients()-> String
}
class SimpleCoffe: Coffe {
func getCost() -> Double {
return 1.0
}
func getIngredients() -> String {
return "Coffe"
}
}
我们定义了一个Protocol,所有的class均继承于此【目的是继承类型,而不是继承行为】
下面是装饰器
class
CoffeDecorator:
Coffe
{
private var coffe: Coffe
required init ( coffe: Coffe ){
self . coffe = coffe
}
func getCost() -> Double {
return self . coffe . getCost ()
}
func getIngredients() -> String {
return self . coffe . getIngredients ()
}
private var coffe: Coffe
required init ( coffe: Coffe ){
self . coffe = coffe
}
func getCost() -> Double {
return self . coffe . getCost ()
}
func getIngredients() -> String {
return self . coffe . getIngredients ()
}
}
下面我们给Coffee添加点糖
class
Milk:
CoffeDecorator
{
required init (coffe: Coffe ) {
super . init (coffe: coffe)
}
override func getCost() -> Double {
return self . coffe . getCost () + Double ( 2.0 )
}
override func getIngredients() -> String {
return super . coffe . getIngredients ()+ " 给加了点纯牛奶 "
}
required init (coffe: Coffe ) {
super . init (coffe: coffe)
}
override func getCost() -> Double {
return self . coffe . getCost () + Double ( 2.0 )
}
override func getIngredients() -> String {
return super . coffe . getIngredients ()+ " 给加了点纯牛奶 "
}
}
还记得刚才的【继承的目的是继承类型,不是行为】
var
simpleCoffe:
Coffe
? =
SimpleCoffe
()
println ( simpleCoffe )
println ( " \ ( simpleCoffe !. getCost () ) \ ( simpleCoffe !. getIngredients () )" )
simpleCoffe = Milk (coffe: simpleCoffe !)
print ( " \ ( simpleCoffe !. getCost () ) \ ( simpleCoffe !. getIngredients () )" )
println ( simpleCoffe )
println ( " \ ( simpleCoffe !. getCost () ) \ ( simpleCoffe !. getIngredients () )" )
simpleCoffe = Milk (coffe: simpleCoffe !)
print ( " \ ( simpleCoffe !. getCost () ) \ ( simpleCoffe !. getIngredients () )" )
println
(
simpleCoffe
)
琮打印我们看到装饰之后具体类型变了,但是根源没变都是Coffee【继承于统一根源,是为了同源】
装饰之后还是调用那几中方法【目的不是继承行为,因为装饰之后还是那些行为】
其实这个更多是用于添加外形,粉饰一新,盖头换面
比较典型的就是游戏角色,的装饰,武器等的扩展,绚丽的衣着
装饰者模式的设计原则为:对扩展开放、对修改关闭,这句话体现在我如果想扩展被装饰者类的行为,无须修改装饰者抽象类,只需继承装饰者抽象类,实现额外的一些装饰或者叫行为即可对被装饰者进行包装。所以:扩展体现在继承、修改体现在子类中,而不是具体的抽象类,这充分体现了依赖倒置原则,这是自己理解的装饰者模式。