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

设计要点



总结

相关推荐
秋水丶秋水1 分钟前
电脑桌面太单调,用Python写一个桌面小宠物应用。
开发语言·python·宠物
人有一心2 分钟前
【论文阅读】多任务学习起源类论文《Multi-Task Feature Learning》
论文阅读·学习
HaiQinyanAN6 分钟前
【学习笔记】虚函数+虚析构函数
c++·笔记·学习
虾球xz17 分钟前
CppCon 2015 学习:Give me fifteen minutes and I’ll change your view of GDB
开发语言·c++·学习
alpszero27 分钟前
使用VSCode开发Django指南
vscode·python·django·sqlite
Sleepless_斑马33 分钟前
【FFmpeg学习(2)】视频概念
学习·ffmpeg·音视频
大数据魔法师38 分钟前
MongoDB(八) - MongoDB GridFS介绍及使用Python操作GridFS
数据库·python·mongodb
止于怠42 分钟前
学习时困了怎么办
学习·解困
weixin_377634841 小时前
【python异步多线程】异步多线程爬虫代码示例
开发语言·爬虫·python
struggle20251 小时前
PennyLane 是一个用于量子计算、量子机器学习和量子化学的跨平台 Python 库。由研究人员构建,用于研究
python·量子计算