装饰器模式
一、定义
装饰器模式能够动态地将向一个现有对象添加功能而不改变其结构。装饰者通过创建一个与原类同类型的装饰类包装现有类,扩展了原类的功能。
二、例子
奶茶与调料,除了最基本的水以外,构成不同奶茶的元素就只有调料。
三、结构
代码实现:
class Drink(object):
m_Name = None
m_Cost = None
def GetDescription(self):
return self.m_Name
def Cost(self):
return self.m_Cost
class MilkTea(Drink):
def __init__(self, Name, Cost):
self.m_Name = Name
self.m_Cost = Cost
class Decorater(Drink):
m_State = {}
def __init__(self, MilkTea):
self.m_MilkTea = MilkTea
def Cost(self):
return self.m_Cost + self.m_MilkTea.Cost()
def GetDescription(self):
return self.m_Name + self.m_MilkTea.GetDescription()
class Bubble(Decorater):
m_Name = "奶盖"
m_Cost = 5
def SetState(self):
if self.m_MilkTea.m_State:
self.m_State = self.m_MilkTea.m_State
self.m_State["IsBubble"] = 1
class Coconut(Decorater):
m_Name = "椰冻"
m_Cost = 2
def SetState(self):
if self.m_MilkTea.m_State:
self.m_State = self.m_MilkTea.m_State
self.m_State["IsCoconut"] = 1
class DecoratorTest(object):
def Run(self):
MilkTeaTest = MilkTea("奶茶", 12)
print "-"*10,"MilkTeaTest","-"*10
print MilkTeaTest.GetDescription()
print "花费了{}元".format(MilkTeaTest.Cost())
BubbleTest = Bubble(MilkTeaTest)
print "-"*10,"BubbleTest","-"*10
print BubbleTest.GetDescription()
print "花费了{}元".format(BubbleTest.Cost())
CoconutTest = Coconut(BubbleTest)
print "-"*10,"CoconutTest","-"*10
print CoconutTest.GetDescription()
print "花费了{}元".format(CoconutTest.Cost())
Test = DecoratorTest()
Test.Run()
测试结果
四、优点
1、装饰类和原类可以独立实现,不会相互耦合,装饰模式可以动态扩展一个实现类的功能。
2、可替代继承。
五、缺点
1、多层修饰比较复杂,会产生许多小对象。