定义
模板方法模式在一个方法中定义算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以在不改变算法结构的情况下,重新定义算法中的步骤。
模板方法定义了一个算法的步骤,允许子类 为一个或者多个步骤提供实现。
钩子函数是一种声明在抽象类中的方法,但只有空的或者默认的实现,钩子的存在,可以让子类有能力对算法的不同点进行挂钩,可以不同的行为。
优点
类图
python编程实现
from abc import abstractmethod
class CaffeineBeverage:
def __init__(self):
pass
def prepare_recipe(self):
self.boil_water()
self.brew()
self.pour_in_cup()
self.add_condiments()
def boil_water(self):
print("Boiling water!")
def pour_in_cup(self):
print("Pouring into cup!")
@abstractmethod
def brew(self):
pass
@abstractmethod
def add_condiments(self):
pass
class Tea(CaffeineBeverage):
def brew(self):
print("Steeping the tea")
def add_condiments(self):
print("Adding Lemon!")
class Coffee(CaffeineBeverage):
def brew(self):
print("Dripping Coffee throught filter!")
def add_condiments(self):
print("Adding Sugar and milk!")
def test_template():
tea = Tea()
coffee = Coffee()
tea.prepare_recipe()
print("=====================")
coffee.prepare_recipe()
if __name__ == "__main__":
test_template()