📅  最后修改于: 2023-12-03 15:10:57.394000             🧑  作者: Mango
模板方法模式是一种行为设计模式,它定义了一个算法的骨架,将一些步骤延迟到子类中实现,以允许在不改变算法结构的情况下重新定义算法的某些步骤。
from abc import ABC, abstractmethod
class Algorithm(ABC):
def run(self):
self.step1()
self.step2()
self.step3()
@abstractmethod
def step1(self):
pass
@abstractmethod
def step2(self):
pass
@abstractmethod
def step3(self):
pass
class ConcreteAlgorithm1(Algorithm):
def step1(self):
print("ConcreteAlgorithm1: Step 1")
def step2(self):
print("ConcreteAlgorithm1: Step 2")
def step3(self):
print("ConcreteAlgorithm1: Step 3")
class ConcreteAlgorithm2(Algorithm):
def step1(self):
print("ConcreteAlgorithm2: Step 1")
def step2(self):
print("ConcreteAlgorithm2: Step 2")
def step3(self):
print("ConcreteAlgorithm2: Step 3")
if __name__ == '__main__':
algorithm1 = ConcreteAlgorithm1()
algorithm1.run()
algorithm2 = ConcreteAlgorithm2()
algorithm2.run()
代码输出:
ConcreteAlgorithm1: Step 1
ConcreteAlgorithm1: Step 2
ConcreteAlgorithm1: Step 3
ConcreteAlgorithm2: Step 1
ConcreteAlgorithm2: Step 2
ConcreteAlgorithm2: Step 3
在示例代码中,定义了一个抽象基类 Algorithm 和两个具体实现类 ConcreteAlgorithm1 和 ConcreteAlgorithm2。Algorithm 类定义了一个 run() 方法来运行算法,该方法依次运行 step1()、step2()、step3() 方法。由于这些方法是抽象的,因此在编写子类时必须实现它们。ConcreteAlgorithm1 和 ConcreteAlgorithm2 继承 Algorithm 并实现了它们自己的步骤实现。最后,可以创建具体对象并调用 run() 方法来运行算法。