基于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
添加奶和糖
"""

设计要点



总结

相关推荐
好奇龙猫14 分钟前
【AI学习-comfyUI学习-第三十节-第三十一节-FLUX-SD放大工作流+FLUX图生图工作流-各个部分学习】
人工智能·学习
沈浩(种子思维作者)22 分钟前
真的能精准医疗吗?癌症能提前发现吗?
人工智能·python·网络安全·健康医疗·量子计算
saoys22 分钟前
Opencv 学习笔记:图像掩膜操作(精准提取指定区域像素)
笔记·opencv·学习
njsgcs1 小时前
ue python二次开发启动教程+ 导入fbx到指定文件夹
开发语言·python·unreal engine·ue
io_T_T1 小时前
迭代器 iteration、iter 与 多线程 concurrent 交叉实践(详细)
python
电子小白1231 小时前
第13期PCB layout工程师初级培训-1-EDA软件的通用设置
笔记·嵌入式硬件·学习·pcb·layout
华研前沿标杆游学1 小时前
2026年走进洛阳格力工厂参观游学
python
Carl_奕然2 小时前
【数据挖掘】数据挖掘必会技能之:A/B测试
人工智能·python·数据挖掘·数据分析
xiaolyuh1232 小时前
Spring 框架 核心架构设计 深度详解
spring·设计模式·spring 设计模式
唯情于酒2 小时前
Docker学习
学习·docker·容器