装饰者模式以对客户透明的方式动态地给一个对象附加上更多的责任,例如生活中常用的生日蛋糕,可以添加蓝莓,巧克力来装饰,可以动态地给一个对象添加额外的职责.
Cake类:
class Cake {
func cakeTypeName() -> String { return "" }
func make() { }
}
class BirthdayCake: Cake {
override func cakeTypeName() -> String {
return "生日"
}
override func make() {
let name = cakeTypeName()
print("\(name)---蛋糕制作成功")
}
}
装饰者对象:
class FruitsDecorator: Cake {
var cake:Cake?
convenience init(cake:Cake) {
self.init()
self.cake = cake
}
override func cakeTypeName() -> String {
return "水果"
}
override func make() {
let name = cakeTypeName()
print("\(name)---蛋糕制作成功")
}
}
class ChocolateDecorator: FruitsDecorator {
convenience init(cake:Cake) {
self.init()
self.cake = cake
}
override func cakeTypeName() -> String {
let name:String = "巧克力" + self.cake!.cakeTypeName()
return name
}
}
class BlueberryDecorator: FruitsDecorator {
convenience init(cake:Cake) {
self.init()
self.cake = cake
}
override func cakeTypeName() -> String {
let name:String = "蓝莓" + self.cake!.cakeTypeName()
return name
}
}
测试代码:
let cake:Cake = BirthdayCake()
cake.make()
let cake2:Cake = ChocolateDecorator(cake: cake)
cake2.make()
let cake3:Cake = BlueberryDecorator(cake: cake)
cake3.make()
let cake4:Cake = BlueberryDecorator(cake: cake2)
cake4.make()
print("FlyElephant")
通过例子中可以看到装饰者和被装饰者有相同的方法,有以下几个有点:
① 装饰者模式在不改变原对象的情况下,为类添加了新的功能.
② 装饰者模式可以通过新增的功能进行排列组合生成不同的类,有很好的扩展性.
装饰者模式最大的缺点会因为过度设计生成各种各样功能相似的小类.