刘刚刚的个人博客

HeadFirst 设计模式--模板方法模式(Template Method)

创建时间:2022-12-26 00:08:26
更新时间:2022-12-26 00:08:26

工厂模式是一种特殊的模板方法模式

模板方法模式(Template Method)

模板方法模式通过再一个方法中定义一个骨架,而将一些步骤延迟到子类中定义。模板方法使得子类可以再不改变算法结构的情况下,重新定义算法中的某些步骤。

示例

在书中,通过咖啡和茶的制作过程介绍了模板方法模式

# 正常情况的实现
class Coffee:

    def prepare_recipe(self):
        self.boil_water()
        self.brew_coffee_grinds()
        self.pour_in_cup()
        self.add_sugar_and_milk()

    def boil_water(self):
        print("煮水")

    def brew_coffee_grinds(self):
        print("将咖啡通过滤网倒入")

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

    def add_sugar_and_milk(self):
        print("加糖和牛奶")


class Tea:

    def prepare_recipe(self):
        self.boil_water()
        self.steep_tea_bag()
        self.pour_in_cup()
        self.add_lemon()

    def boil_water(self):
        print("煮水")

    def steep_tea_bag(self):
        print("泡茶包")

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

    def add_lemon(self):
        print("添加柠檬")

# 通过模板方法实现
from abc import ABC, abstractmethod


class CaffeineBeverage(ABC):

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

    def boil_water(self):
        print("煮水")

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

    @abstractmethod
    def brew(self):
        pass

    @abstractmethod
    def add_condiments(self):
        pass


class Coffee(CaffeineBeverage):

    def brew(self):
        print("将咖啡通过滤网倒入")

    def add_condiments(self):
        print("加糖和牛奶")


class Tea(CaffeineBeverage):

    def brew(self):
        print("泡茶包")

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

设计原则:好莱坞原则

原则:别调用我们,我们会调用你。

通过该原则,可以防止低层组件与高层组件的相互依赖。

与策略模式的比较

策略模式使用组合实现了方法的灵活调用,及在使用过程中的灵活改变。

而模板方法模式是通过继承实现的。

我的名片

昵称:shuta

职业:后台开发(python、php)

邮箱:648949076@qq.com

站点信息

建站时间: 2020/2/19
网站程序: ANTD PRO VUE + TP6.0
晋ICP备18007778号