装饰器模式能够实现动态的为对象添加功能,是从一个对象外部来给对象添加功能。装饰器模式就是基于对象组合的方式,可以很灵活的给对象添加所需要的功能。
protocol Coffee {
func getCost() -> Double
func getIngredients() -> String
}
class SimpleCoffee: Coffee {
func getCost() -> Double {
return 1.0
}
func getIngredients() -> String {
return "Coffee"
}
}
class CoffeeDecorator: Coffee {
private let decoratedCoffee: Coffee
fileprivate let ingredientSeparator: String = ", "
required init(decoratedCoffee: Coffee) {
self.decoratedCoffee = decoratedCoffee
}
func getCost() -> Double {
return decoratedCoffee.getCost()
}
func getIngredients() -> String {
return decoratedCoffee.getIngredients()
}
}
final class Milk: CoffeeDecorator {
required init(decoratedCoffee: Coffee) {
super.init(decoratedCoffee: decoratedCoffee)
}
override func getCost() -> Double {
return super.getCost() + 0.5
}
override func getIngredients() -> String {
return super.getIngredients() + ingredientSeparator + "Milk"
}
}
final class WhipCoffee: CoffeeDecorator {
required init(decoratedCoffee: Coffee) {
super.init(decoratedCoffee: decoratedCoffee)
}
override func getCost() -> Double {
return super.getCost() + 0.7
}
override func getIngredients() -> String {
return super.getIngredients() + ingredientSeparator + "Whip"
}
}
/*:
### Usage:
*/
var someCoffee: Coffee = SimpleCoffee()
print("Cost : \(someCoffee.getCost()); Ingredients: \(someCoffee.getIngredients())")
someCoffee = Milk(decoratedCoffee: someCoffee)
print("Cost : \(someCoffee.getCost()); Ingredients: \(someCoffee.getIngredients())")
someCoffee = WhipCoffee(decoratedCoffee: someCoffee)
print("Cost : \(someCoffee.getCost()); Ingredients: \(someCoffee.getIngredients())")
网友评论