📜  模板方法 - Python设计模式(1)

📅  最后修改于: 2023-12-03 15:10:57.394000             🧑  作者: Mango

模板方法 - Python设计模式

模板方法模式是一种行为设计模式,它定义了一个算法的骨架,将一些步骤延迟到子类中实现,以允许在不改变算法结构的情况下重新定义算法的某些步骤。

优点
  1. 清晰地定义了算法的步骤,使得算法实现更加简单、可维护和可扩展。
  2. 通过提供一个默认实现并允许子类覆盖部分步骤,使得算法实现更加灵活。
  3. 将公共代码提取到父类中,避免了重复代码。
缺点
  1. 如果算法的结构发生变化,所有的子类都必须进行修改。
  2. 如果模板方法中定义的具体步骤过多,会导致类的数量增加。
应用场景
  1. 当多个类具有相同的算法结构,但某些步骤可能存在不同的实现时,可以使用模板方法模式。
  2. 当需要一种算法的变体或扩展时,可以使用模板方法模式。
示例代码
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() 方法来运行算法。