模板方法模式:
应用特性:重复做相同逻辑的事情,但是具体细节不同的场景
结构特性:相同逻辑抽取至父类,具体细节留置子类。可以说是对逻辑的抽象
UML:
#!/usr/bin/env python
#encoding: utf-8
class template:
def __init__(self):
pass
def logic(self):
print 'do something before ....'
print self.do_something_now()
print 'do something after ....'
def do_something_now(self):
return None
class apply_temp1(template):
def __init__(self):
pass
def do_something_now(self):
return 'apply 1'
class apply_temp2(template):
def __init__(self):
pass
def do_something_now(self):
return 'apply 2'
if '__main__' == __name__:
obj1 = apply_temp1()
obj2 = apply_temp2()
obj1.logic()
obj2.logic()
print obj1.__class__
print obj2.__class__
结果:
do something before ....
apply 1
do something after ....
do something before ....
apply 2
do something after ....
__main__.apply_temp1
__main__.apply_temp2