策略模式:
应用特性:接收任意对象,然后对不同的对象去做相同的一件事情。
结构特性:策略模式其实是利用了多态的特性,使用固定的方法,但是把对象作为个体抽离出来了,对象在这里有点象抽离出来的配置文件的意思
UML:
#!/usr/bin/env python
#encoding: utf-8
class 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__.setclass
class1:dosomething1
class2:dosomething2
class3:dosomething3