基于Python学习《Head First设计模式》第八章 模板方法模式

项目:星巴兹咖啡和茶



代码实现

python 复制代码
from abc import abstractmethod


class CaffeineBeverage:
    """咖啡饮料"""

    def prepare_recipe(self):
        self.boil_water()
        self.brew()
        self.pour_in_cup()
        self.add_condiments()

    def boil_water(self):
        print('将水煮沸')

    @abstractmethod
    def brew(self):
        print('浸泡或冲泡')

    def pour_in_cup(self):
        print('倒入杯子')

    @abstractmethod
    def add_condiments(self):
        print('添加调料')


class Tea(CaffeineBeverage):
    def brew(self):
        print('浸泡茶叶')

    def add_condiments(self):
        print('添加柠檬')


class Coffee(CaffeineBeverage):
    def brew(self):
        print('冲泡咖啡')

    def add_condiments(self):
        print('添加奶和糖')

if __name__ == '__main__':
    tea = Tea()
    tea.prepare_recipe()
    print()
    coffee = Coffee()
    coffee.prepare_recipe()
    
"""运行结果:
将水煮沸
浸泡茶叶
倒入杯子
添加柠檬

将水煮沸
冲泡咖啡
倒入杯子
添加奶和糖
"""

认识模板方法


模板方法定义


挂钩模板方法


代码实现钩子模板方法

python 复制代码
from abc import abstractmethod


class CaffeineBeverageWithHook:
    """咖啡饮料"""

    def prepare_recipe(self):
        self.boil_water()
        self.brew()
        self.pour_in_cup()
        if self.customer_wants_condiments():
            self.add_condiments()

    def boil_water(self):
        print('将水煮沸')

    @abstractmethod
    def brew(self):
        print('浸泡或冲泡')

    def pour_in_cup(self):
        print('倒入杯子')

    @abstractmethod
    def add_condiments(self):
        print('添加调料')

    def customer_wants_condiments(self):
        return True


class TeaHook(CaffeineBeverageWithHook):
    def brew(self):
        print('浸泡茶叶')

    def add_condiments(self):
        print('添加柠檬')


class CoffeeWithHook(CaffeineBeverageWithHook):
    def brew(self):
        print('冲泡咖啡')

    def add_condiments(self):
        print('添加奶和糖')

    def get_user_input(self):
        answer = input('Would you like milk and sugar with your coffe? (y/n)')
        return 'no' if not answer else answer

    def customer_wants_condiments(self):
        answer = self.get_user_input()
        if answer.lower().startswith('y'):
            return True
        return False


if __name__ == '__main__':
    tea_hook = TeaHook()
    coffee_hook = CoffeeWithHook()

    print('制作茶...')
    tea_hook.prepare_recipe()

    print('\n制作咖啡...')
    coffee_hook.prepare_recipe()

"""运行结果:
制作茶...
将水煮沸
浸泡茶叶
倒入杯子
添加柠檬

制作咖啡...
将水煮沸
冲泡咖啡
倒入杯子
Would you like milk and sugar with your coffe? (y/n)y
添加奶和糖
"""

设计要点



总结

相关推荐
CAE3202 小时前
基于机器学习的智能垃圾短信检测超强系统
人工智能·python·机器学习·自然语言处理·垃圾短信拦截
MarcoPage3 小时前
Python 字典推导式入门:一行构建键值对映射
java·linux·python
im_AMBER6 小时前
React 17
前端·javascript·笔记·学习·react.js·前端框架
谷歌开发者7 小时前
Web 开发指向标 | Chrome 开发者工具学习资源 (六)
前端·chrome·学习
ζั͡山 ั͡有扶苏 ั͡✾8 小时前
从零搭建 Data-Juicer:一站式大模型数据预处理与可视化平台完整教程
python·data-juicer
QT 小鲜肉8 小时前
【QT/C++】Qt定时器QTimer类的实现方法详解(超详细)
开发语言·数据库·c++·笔记·qt·学习
SkylerHu9 小时前
tornado+gunicorn部署设置max_body_size
python·tornado·gunicorn
执笔论英雄9 小时前
【大模型训练】加载load_state 中的一些技巧 工厂设计模式
设计模式
Mr.Jessy9 小时前
Web APIs 学习第五天:日期对象与DOM节点
开发语言·前端·javascript·学习·html
存在morning9 小时前
【人工智能学习笔记 三】 AI教学之前端跨栈一:React整体分层架构
笔记·学习·架构