跳转至

装饰模式

装饰模式

装饰模式(Decorator Pattern)是一种结构型设计模式,它允许在不改变对象接口的情况下,动态地给一个对象增加额外的职责。装饰模式通过创建一系列装饰类来包装原始对象,从而扩展其功能。

装饰模式的特点

  1. 动态增加行为:在不修改类的情况下,动态地扩展对象的功能。
  2. 遵循开放/封闭原则:通过组合而不是继承来扩展类的功能,使类对扩展开放而对修改封闭。
  3. 灵活性高:可以对一个对象应用多个装饰器,从而灵活地组合各种行为。

装饰模式的结构

  1. 组件(Component):定义了可以被装饰的对象接口。
  2. 具体组件(Concrete Component):实现组件接口的类,可以被装饰器装饰。
  3. 装饰器(Decorator):实现组件接口,并包含一个指向组件实例的引用。
  4. 具体装饰器(Concrete Decorators):继承装饰器类,扩展其功能。

装饰模式的Python实现

以下是装饰模式在Python中的一个实现示例:

1. 定义组件接口和具体组件类

from abc import ABC, abstractmethod

class Component(ABC):
    @abstractmethod
    def operation(self) -> str:
        pass

class ConcreteComponent(Component):
    def operation(self) -> str:
        return "ConcreteComponent"

2. 定义装饰器类和具体装饰器类

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

    def operation(self) -> str:
        return self._component.operation()

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

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

3. 客户端代码

def client_code(component: Component) -> None:
    print(f"RESULT: {component.operation()}")

if __name__ == "__main__":
    # 原始对象
    simple = ConcreteComponent()
    print("Client: I've got a simple component:")
    client_code(simple)
    print("\n")

    # 使用装饰器A装饰
    decorator1 = ConcreteDecoratorA(simple)
    print("Client: Now I've got a decorated component with ConcreteDecoratorA:")
    client_code(decorator1)
    print("\n")

    # 使用装饰器B再装饰
    decorator2 = ConcreteDecoratorB(decorator1)
    print("Client: Now I've got a decorated component with ConcreteDecoratorA and ConcreteDecoratorB:")
    client_code(decorator2)

运行结果

Client: I've got a simple component:
RESULT: ConcreteComponent

Client: Now I've got a decorated component with ConcreteDecoratorA:
RESULT: ConcreteDecoratorA(ConcreteComponent)

Client: Now I've got a decorated component with ConcreteDecoratorA and ConcreteDecoratorB:
RESULT: ConcreteDecoratorB(ConcreteDecoratorA(ConcreteComponent))

说明

  1. 组件(Component):定义了可以被装饰的对象接口,包括一个operation方法。
  2. 具体组件(ConcreteComponent):实现了组件接口,是可以被装饰的具体对象。
  3. 装饰器(Decorator):实现了组件接口,并包含一个指向组件实例的引用,通过组合而不是继承来扩展类的功能。
  4. 具体装饰器(ConcreteDecoratorA 和 ConcreteDecoratorB):继承装饰器类,扩展其功能,并在调用operation方法时增加额外的行为。

通过装饰模式,可以动态地增加或修改对象的行为,而无需修改原始类代码或使用继承,从而提高代码的灵活性和可扩展性。装饰模式特别适用于需要动态扩展对象功能的场景,例如图形界面组件、日志记录等。

评论