设计模式之python版(七)--模板方法模式

模板方法模式:

应用特性:重复做相同逻辑的事情,但是具体细节不同的场景

结构特性:相同逻辑抽取至父类,具体细节留置子类。可以说是对逻辑的抽象

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

    原文作者:像风一样的自由
    原文地址: https://blog.csdn.net/five3/article/details/7564578
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞