前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >模板方法模式

模板方法模式

作者头像
用户2936342
发布2018-08-27 14:10:20
2690
发布2018-08-27 14:10:20
举报
文章被收录于专栏:nummy

模板方法模式

不知道你有没有注意过,我们实现某个业务功能,在不同的对象会有不同的细节实现, 以前说过策略模式, 策略模式是将逻辑封装在一个类(提到的文章中的Duck)中,然后使用委托的方式解决。 模板方法模式的角度是:把不变的框架抽象出来,定义好要传入的细节的接口. 各产品类的公共的行为 会被提出到公共父类,可变的都在这些产品子类中

示例

代码语言:javascript
复制
import six

class AlooDish(object):
    def get_ingredients(self,):
        self.ingredients = {}

    def prepare_vegetables(self,):
        for item in six.iteritems(self.ingredients):
            print("take {0} {1} and cut into smaller pieces".format(item[0],item[1]))
        print("cut all vegetables in small pieces")

    def fry(self,):
        print("fry for 5 minutes")

    def serve(self,):
        print("Dish is ready to be served")

    def cook(self,):
        self.get_ingredients()
        self.prepare_vegetables()
        self.fry()
        self.serve()

class AlooMatar(AlooDish):
    def get_ingredients(self,):
        self.ingredients = {'aloo':"1 Kg",'matar':"1/2 kg"}

    def fry(self,):
        print("wait 10 min")

class AlooPyaz(AlooDish):
    def get_ingredients(self):
        self.ingredients = {'aloo':"1 Kg",'pyaz':"1/2 kg"}

aloomatar = AlooMatar()
aloopyaz = AlooPyaz()
print("*******************  aloomatar cook")
aloomatar.cook()
print("******************* aloopyaz cook")
aloopyaz.cook()

在上面的例子中,我们将公共的步骤抽象出来,放在父类中,而将不同的部分,实现在子类中。

输出结果为

代码语言:javascript
复制
*******************  aloomatar cook
take aloo 1 Kg and cut into smaller pieces
take matar 1/2 kg and cut into smaller pieces
cut all vegetables in small pieces
wait 10 min
Dish is ready to be served
******************* aloopyaz cook
take pyaz 1/2 kg and cut into smaller pieces
take aloo 1 Kg and cut into smaller pieces
cut all vegetables in small pieces
fry for 5 minutes
Dish is ready to be served
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017.07.06 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 模板方法模式
  • 示例
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档