模板方法模式
模式说明
定义一个操作中的算法的骨架,而将步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义算法的某些特定步骤。
模式结构图
程序示例
说明:泡茶与泡咖啡使用同一套流程
代码:
class Beverage(object): """description of class""" def makeBeverage(self): self.boilWater() self.brew() self.pourInCup() self.addCondiments() def boilWater(self): print 'boil water' def brew(self): print 'brew' def pourInCup(self): print 'pour into cup' def addCondiments(self): print 'add condiments' class Coffee(Beverage): def brew(self): print 'coffee' def addCondiments(self): print 'Adding Sugar and Milk...' class Tea(Beverage): def brew(self): print "tea" def addCondiments(self): print 'Adding Lemon...' if '__main__'==__name__: coffee = Coffee() coffee.makeBeverage() tea = Tea() tea.makeBeverage()
运行结果:
参考来源:
http://www.cnblogs.com/chenssy/p/3679190.html
http://www.cnblogs.com/wuyuegb2312/archive/2013/04/09/3008320.html
http://www.cnblogs.com/zhuxiongfeng/archive/2010/04/09/1708615.html