python设计模式之“装饰者模式”
newbie_evolve
posted @ 2013年8月15日 11:33
in python之年
, 949 阅读
everage:饮料 HouseBlend:混合咖啡 decaf:无咖啡因咖啡 DarkRoast:深度烘焙咖啡
Milk:牛奶 Soy:豆粉 Whip:搅拌机 CondimentDecorator:调味品装饰者
class beverage():
def __init__(self):
pass
def cost(self):
pass
class HouseBlend(beverage):
def __init__(self):
beverage.__init__(self)
def cost(self):
return 1.0
class decaf(beverage):
def __init__(self):
beverage.__init__(self)
def cost(self):
return 2.0
class DarkRoast(beverage):
def __init__(self):
beverage.__init__(self)
def cost(self):
return 4.0
class CondimentDecorator(beverage):
def __init__(self,comp):
beverage.__init__(self)
self.comp = comp
def cost(self):
pass
class Milk(CondimentDecorator):
def __init__(self,com):
CondimentDecorator.__init__(self,com)
def cost(self):
return 10 + self.comp.cost()
class Soy(CondimentDecorator):
def __init__(self,com):
CondimentDecorator.__init__(self,com)
def cost(self):
return 20 + self.comp.cost()
class Whip(CondimentDecorator):
def __init__(self,com):
CondimentDecorator.__init__(self,com)
def cost(self):
return 30 + self.comp.cost()
if __name__ =="__main__":
compont = decaf()
compont = Milk(compont)
compont = Soy(compont)
print compont.cost()
装饰者模式:
一、装饰对象(Decorator)和真实对象(ConcreteDecorator)有相同的接口。如Milk、Soy与decaf
二、装饰(Decorator)对象包含一个真实对象的引用,如decaf的引用:compont
总结:装饰者模式可以动态给一个对象添加一些额外的职责,就增加功能来说,Decorator模式比生成子类更为灵活。