模板方法模式是一种行为型设计模式,它定义了一个算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以在不改变算法结构的情况下重定义算法中的某些步骤。
模式结构
- 抽象类 (AbstractClass): 定义算法的骨架,包括一个模板方法,并定义一个或多个纯虚函数,这些纯虚函数将在子类中被实现。
- 具体类 (ConcreteClass): 实现抽象类中的纯虚函数,以提供算法的不同步骤的具体实现。
- 模板方法 (TemplateMethod): 定义一个算法的骨架,并调用在抽象类中定义的一个或多个纯虚函数。
何时使用
- 当想定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。
- 当想让子类在不改变算法结构的情况下重定义算法中的某个步骤。
示例
假设我们有一个制作咖啡的算法,其中包含以下步骤:
- 加热咖啡机
- 加入咖啡粉
- 加水
- 烹饪咖啡
from abc import ABC, abstractmethod
class CoffeeMaker(ABC):
def __init__(self):
self.__coffee = None
def brew(self):
self.boilWater()
self.addCoffee()
self.addWater()
self.cook()
@abstractmethod
def boilWater(self):
pass
@abstractmethod
def addCoffee(self):
pass
@abstractmethod
def addWater(self):
pass
@abstractmethod
def cook(self):
pass
class AmericanCoffee(CoffeeMaker):
def boilWater(self):
print("Boiling water for American Coffee")
def addCoffee(self):
print("Adding coffee powder for American Coffee")
def addWater(self):
print("Adding water for American Coffee")
def cook(self):
print("Cooking American Coffee")
class Latte(CoffeeMaker):
def boilWater(self):
print("Boiling water for Latte")
def addCoffee(self):
print("Adding coffee powder for Latte")
def addWater(self):
print("Adding milk for Latte")
def cook(self):
print("Cooking Latte")
扩展阅读
更多设计模式的内容,请访问设计模式教程。