裝飾模式:
應用特點:是動態給主功能添加一些裝飾性的功能。
結構特性:就是把各裝飾性的功能和主功能分開,然後根據需要選擇裝飾性的功能來修飾主功能即可。
UML:
#!/usr/bin/env python #encoding: utf-8 ##被裝飾的主類class baseclass: def __init__(self): pass def set_compent(self): pass def pack_something(self): print 'All packed me!' ##串連屬性類別與主類的中介層類class packclass(baseclass): def __init__(self): pass def set_compent(self,compent): if None != compent: self.compent = compent def pack_something(self): self.compent.pack_something() ##修飾主類的屬性類別class newclass1(packclass): def __init__(self): pass def pack_something(self): print 'something1' packclass.pack_something(self)##修飾主類的屬性類別 class newclass2(packclass): def __init__(self): pass def pack_something(self, ): print 'something2' packclass.pack_something(self)##修飾主類的屬性類別 class newclass3(packclass): def __init__(self): pass def pack_something(self): print 'something3' packclass.pack_something(self) if '__main__' == __name__: mainobj = baseclass() class1_obj = newclass1() class2_obj = newclass2() class3_obj = newclass3() print mainobj.__class__ print class1_obj.__class__ print class2_obj.__class__ print class3_obj.__class__ class1_obj.set_compent(mainobj) class2_obj.set_compent(class1_obj) class3_obj.set_compent(class2_obj) class3_obj.pack_something()
結果:
__main__.baseclass__main__.newclass1__main__.newclass2__main__.newclass3something3something2something1All packed mine!