装饰模式
模式模式应用于动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更加灵活。
Component类
class Component:
def Operation(self):
pass
ConcreteComponent类
class ConcreteComponent(Component):
def Operation(self):
pass
Decorator类
class Decorator(Component):
def SetComponent(self, component):
self.component = component
def Operation(self):
if self.component != null :
self.component.Operation(self)
ConcreteDecoratorA 和ConcreteDecoratorB 类
class ConcreteDecoratorA(Decorator):
__addedstate = null
def Operation(self):
Decorator.Operation(self)
self.__addedstate = "New state"
class ConcreteDecoratorB(Decorator):
def Operation(self):
Decorator.Operation(self)
self.__AddedBehavior(self)
def __AddedBehavior(self)
pass
客户端主程序
if __name__ == "__main__":
cc = ConcreteComponent() ##实例化ConcreteComponent
cdA = ConcreteDecoratorA()
cdB = ConcreteDecoratorB()
cdA.SetComponent(cc) ##用cdA装饰cc
cdB.SetComponent(cdA) ##用cdB装饰cdA
cdB.Operation() ##执行cdB的Operation方法
装饰模式是利用SetComponent来对对象进行包装的。每个装饰对象的实现和如何用这个对象分离开。每个装饰对象只关心自己的功能,不需要关心如何被添加到对象链当中。
下图是对人装饰的UML关系图
class Person:
def __init__(self, name):
self.name = name
def Show(self):
print "dressed is %s" %(self.name)
class Finery(Person):
component = None
def Decorate(self, component)
self.component = component
def Show(self):
if self.component != None:
self.component.Show()
class TShits(Finery):
def Show(self):
print "T-Shits"
self.component.Show()
class BigTrousers(Finery):
def Show(self):
print "Trousers"
self.component.Show()
if __name__ == "__main__":
p = Person("SomeBody")
ts = TShits()
bts = BigTrousers()
ts.Decorate(p)
bts.Decorate(ts)
bts.Show()
装饰模式是为已有功能动态的添加更多功能的一种方式。当系统需要新功能的时候,是向旧的类中添加新的代码。这些新的代码通常祈祷装饰原有核心职责或主要行为。
装饰模式有效的类的核心职责和装饰功能区分开,而且可以去除相关类汇总的重复的装饰逻辑。