装饰器(Decorator)模式的定义:
指在不改变现有对象结构的情况下,动态地给该对象增加一些职责(即增加其额外功能)的模式,它属于对象结构型模式
装饰器模式的优缺点如下:
优点:
1.装饰器是继承的有力补充,比继承灵活,在不改变原有对象的情况下,动态的给一个对象扩展功能,即插即用
2.通过使用不用装饰类及这些装饰类的排列组合,可以实现不同效果
3.装饰器模式完全遵守开闭原则
缺点:
1.装饰器模式会增加许多子类,过度使用会增加程序的复杂性
#装饰器模式的实现
class Beverage(): name = "" price = 0.0 type = "BEVERAGE" def getPrice(self): return self.price def setPrice(self,price): self.price = price def getName(self): return self.name class coke(Beverage): def __init__(self): self.name = "coke" self.price = 4.0 class milk(Beverage): def __init__(self): self.name = "milk" self.price = 5.0 class drinkDecorator(): def getName(self): pass def getPrice(self): pass class iceDecorator(drinkDecorator): def __init__(self,Beverage): self.beverage = Beverage def getName(self): return self.beverage.getName() + " + ice" def getPrice(self): return self.beverage.getPrice() + 0.4 class sugarDecorator(drinkDecorator): def __init__(self,Beverage): self.beverage = Beverage def getName(self): return self.beverage.getName() + " + sugar" def getPrice(self): return self.beverage.getPrice() + 0.8 if __name__ == "__main__": milk1 = milk() print(milk1.getPrice(),milk1.getName()) iceMilk = iceDecorator(milk1) print(iceMilk.getPrice(),iceMilk.getName()) cofe1 = coke() print(cofe1.getPrice(),cofe1.getName()) sugarCofe = sugarDecorator(cofe1) print(sugarCofe.getPrice(),sugarCofe.getName())
欢迎大家关注我的微信公众号: