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

设计要点



总结

相关推荐
试着4 分钟前
零基础学习性能测试第五章:JVM性能分析与调优-垃圾回收器的分类与回收
jvm·学习·零基础·性能测试·垃圾回收器
livemetee9 分钟前
Flink2.0学习笔记:Stream API 常用转换算子
大数据·学习·flink
WXX_s12 分钟前
【OpenCV篇】OpenCV——03day.图像预处理(2)
人工智能·python·opencv·学习·计算机视觉
艾莉丝努力练剑1 小时前
【LeetCode&数据结构】二叉树的应用(二)——二叉树的前序遍历问题、二叉树的中序遍历问题、二叉树的后序遍历问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表
花月mmc1 小时前
CanMV-K230 AI学习笔记系列
人工智能·笔记·学习
Jackilina_Stone1 小时前
【论文|复现】YOLOFuse:面向多模态目标检测的双流融合框架
人工智能·python·目标检测·计算机视觉·融合
fengye2071612 小时前
板凳-------Mysql cookbook学习 (十二--------6)
学习·mysql·adb
双叶8362 小时前
(Python)文件储存的认识,文件路径(文件储存基础教程)(Windows系统文件路径)(基础教程)
开发语言·windows·python
喜欢吃燃面2 小时前
C++:list(1)list的使用
开发语言·c++·学习
waveee1232 小时前
学习嵌入式的第三十三天-数据结构-(2025.7.25)服务器/多客户端模型
服务器·数据结构·学习