装饰器模式动态将责任附加到对象上。想要扩展功能,装饰者提供有别于继承的另一种选择。
装饰器模式的特点:
- 继承属于扩展形式之一,但不见得是达到弹性设计的最佳方式
- 在我们的设计中,应该允许行为被扩展,而不用修改现有的代码
- 组合和委托可用在运行时动态的加上新的行为
- 除了继承,装饰者模式也可以让我们扩展行为
- 装饰者模式会导致出现很多小的对象,过度使用,会让程序变的很复杂
- 可以用很很多个装饰者包装一个组件
- 装饰者可以在被装饰者的前面/后面加上自己的行为,甚至将被装饰者的行为整个取代掉,来达到某种目的
- 装饰者模式意味着一群装饰者类,这些类可以用来包装具体的组件
- 装饰者类反映出被装饰者的类型,事实上他们具有相同的类型,都是通过继承或者接口实现
10.装饰者一般对组件的客户是透明的,除非客户依赖于组件的特殊类型
python实现装饰器模式:
"""
装饰器模式
"""
class Beverages(object):
"""
饮料
"""
description = ''
def get_description(self):
return self.description
def cost(self):
raise NotImplementedError()
class Condiment(Beverages):
"""
调味料
"""
def get_description(self):
return self.description
class Espresso(Beverages):
description = "Espresso"
def cost(self):
return 1.99
class HouseBlend(Beverages):
"""
家庭混合
"""
description = "HouseBlend"
def cost(self):
return 0.89
class Mocha(Condiment):
description = "Mocha"
def __init__(self, beverage):
self.beverage = beverage
def get_description(self):
return self.description + " " + self.beverage.get_description()
def cost(self):
return 0.2 + self.beverage.cost()
if __name__ == "__main__":
house_blent = HouseBlend()
mocha_house_blend = Mocha(house_blent)
cost = mocha_house_blend.cost()
print(mocha_house_blend.get_description() + " cost: %s" % cost)
espresso = Espresso()
mocha_espress = Mocha(espresso)
cost = mocha_espress.cost()
print(mocha_espress.get_description() + ' cost: %s ' % cost)
备注:
博客中有关设计模式的例子都是《head first 设计模式》中的例子,只不过是用python实现