1. 策略模式 (Strategy Pattern)

核心思想:定义一组算法,将每个算法都封装起来,并使它们可以相互替换。策略模式让算法的变化独立于使用算法的客户。

应用场景:当你的程序中有多种算法完成同一任务,且这些算法可能需要在运行时切换时,使用策略模式可以让你轻松地在不同算法间切换。

Python示例:

python

from abc import ABC, abstractmethod

class Strategy(ABC):
    @abstractmethod
    def do_algorithm(self, data):
        pass

class ConcreteStrategyA(Strategy):
    def do_algorithm(self, data):
        return sorted(data)

class ConcreteStrategyB(Strategy):
    def do_algorithm(self, data):
        return reversed(sorted(data))

class Context:
    def __init__(self, strategy):
        self._strategy = strategy

    @property
    def strategy(self):
        return self._strategy

    @strategy.setter
    def strategy(self, strategy):
        self._strategy = strategy

    def execute_strategy(self, data):
        return self._strategy.do_algorithm(data)

# 使用示例
context = Context(ConcreteStrategyA())
print(context.execute_strategy([1, 3, 2]))# 输出排序后的列表

context.strategy = ConcreteStrategyB()
print(context.execute_strategy([1, 3, 2]))# 输出倒序排序后的列表

2. 工厂方法模式 (Factory Method Pattern)

核心思想:定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。

应用场景:当你不想在客户端代码中硬编码具体类的实例化逻辑,而希望将这一过程抽象出来,以便在不修改客户端代码的情况下引入新的产品类时,可以使用工厂方法模式。

Python示例:

python

from abc import ABC, abstractmethod

class Product(ABC):
    @abstractmethod
    def operation(self):
        pass

class ConcreteProductA(Product):
    def operation(self):
        return "ConcreteProductA"

class ConcreteProductB(Product):
    def operation(self):
        return "ConcreteProductB"

class Creator:
    @staticmethod
    def factory_method(product_type):
        if product_type == "A":
            return ConcreteProductA()
        elif product_type == "B":
            return ConcreteProductB()
        else:
            raise ValueError("Invalid product type")

def client_code(creator):
    product = creator.factory_method("A")
    print(product.operation())

client_code(Creator)

3. 模板方法模式 (Template Method Pattern)

核心思想:定义一个操作中的算法骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。

应用场景:当一系列算法遵循相同的总体步骤,但某些步骤的具体实现可能不同时,可以使用模板方法模式。

Python示例:

python

from abc import ABC, abstractmethod

class AbstractClass(ABC):
    def template_method(self):
        self.base_operation1()
        self.required_operations1()
        self.base_operation2()
        self.hook()

    def base_operation1(self):
        print("Base operation 1")

    def base_operation2(self):
        print("Base operation 2")

    @abstractmethod
    def required_operations1(self):
        pass

    def hook(self):
        pass# 可以被子类覆盖,也可以不覆盖

class ConcreteClass(AbstractClass):
    def required_operations1(self):
        print("Required operations 1")

    def hook(self):
        print("Hook is overridden")

# 使用示例
concrete = ConcreteClass()
concrete.template_method()

4. 装饰器模式 (Decorator Pattern)

核心思想:动态地给一个对象添加一些额外的职责,就增加功能来说,装饰器模式相比生成子类更为灵活。

应用场景:当需要为对象动态添加功能,且这些功能可以独立于其他功能组合时,装饰器模式非常有用。

Python示例:

python

class Component:
    def operation(self):
        pass

class ConcreteComponent(Component):
    def operation(self):
        return "ConcreteComponent operation"

class Decorator(Component):
    def __init__(self, component):
        self._component = component

    def operation(self):
        return self._component.operation()

class ConcreteDecoratorA(Decorator):
    def operation(self):
        return f"ConcreteDecoratorA({self._component.operation()})"

class ConcreteDecoratorB(Decorator):
    def operation(self):
        return f"ConcreteDecoratorB({self._component.operation()})"

# 使用示例
component = ConcreteComponent()
decorator_a = ConcreteDecoratorA(component)
decorator_b = ConcreteDecoratorB(decorator_a)

print(decorator_b.operation())# 输出: ConcreteDecoratorB(ConcreteDecoratorA(ConcreteComponent operation))