码迷,mamicode.com
首页 > 其他好文 > 详细

模板方法模式

时间:2014-08-25 18:37:14      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   使用   io   ar   2014   

模式说明

定义一个操作中的算法的骨架,而将步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义算法的某些特定步骤。

模式结构图

bubuko.com,布布扣

程序示例

说明:泡茶与泡咖啡使用同一套流程

代码:

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()

运行结果:

bubuko.com,布布扣

参考来源:

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

 

模板方法模式

标签:des   style   blog   http   color   使用   io   ar   2014   

原文地址:http://www.cnblogs.com/wang-shuai/p/3935321.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!