策略模式:
應用特性:接收任意對象,然後對不同的對象去做相同的一件事情。
結構特性:策略模式其實是利用了多態的特性,使用固定的方法,但是把對象作為個體抽離出來了,對象在這裡有點象抽離出來的設定檔的意思
UML:
#!/usr/bin/env python#encoding: utf-8class baseclass: def __init__(self): pass def dosomething(self): pass class newclass1(baseclass): def __init__(self): pass def dosomething(self, perfix): print perfix + ':dosomething1' class newclass2(baseclass): def __init__(self): pass def dosomething(self, perfix): print perfix + ':dosomething2' class newclass3(baseclass): def __init__(self): pass def dosomething(self, perfix): print perfix + ':dosomething3' class setclass: def __init__(self,something): if 'newclass1' == something: self.classobj = newclass1() elif 'newclass2' == something: self.classobj = newclass2() elif 'newclass3' == something: self.classobj = newclass3() else: return None def dosomething(self,perfix): self.classobj.dosomething(perfix) if '__main__' == __name__: class1 = setclass('newclass1') class2 = setclass('newclass2') class3 = setclass('newclass3') print class1.__class__ print class2.__class__ print class3.__class__ class1.dosomething('class1') class2.dosomething('class2') class3.dosomething('class3')
結果:
__main__.setclass__main__.setclass__main__.setclassclass1:dosomething1class2:dosomething2class3:dosomething3