基于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 天前
Flutter 框架跨平台鸿蒙开发 - 恐惧清单应用
学习·flutter·华为·开源·harmonyos·鸿蒙
yuzhuanhei1 天前
Visual Studio 配置C++opencv
c++·学习·visual studio
Csvn1 天前
🌟 LangChain 30 天保姆级教程 · Day 13|OutputParser 进阶!让 AI 输出自动转为结构化对象,并支持自动重试!
python·langchain
cch89181 天前
Python主流框架全解析
开发语言·python
Momentary_SixthSense1 天前
设计模式之工厂模式
java·开发语言·设计模式
Java码农也是农1 天前
Multi-Agent 系统设计模式
设计模式·agent·multi-agent
sg_knight1 天前
设计模式实战:状态模式(State)
python·ui·设计模式·状态模式·state
好运的阿财1 天前
process 工具与子agent管理机制详解
网络·人工智能·python·程序人生·ai编程
此刻觐神1 天前
IMX6ULL开发板学习-01(Linux文件目录和目录相关命令)
linux·服务器·学习
张張4081 天前
(域格)环境搭建和编译
c语言·开发语言·python·ai