装饰器模式是一种结构型设计模式,它允许你在不修改对象结构的情况下,动态地将责任附加到对象上,这种模式通常用于在运行时为对象添加新的行为或功能,而无需创建子类,装饰器模式的核心思想是通过一个统一的接口来包装不同的对象,从而实现对这些对象的统一管理。
以下是一个简单的装饰器模式示例:
Python
from abc import ABC, abstractmethod
抽象组件(Component)
class Component(ABC):
@abstractmethod
def operation(self):
pass
具体组件(ConcreteComponent)
class ConcreteComponent(Component):
def operation(self):
return "具体组件的操作"
抽象装饰器(Decorator)
class Decorator(ABC):
def __init__(self, component: Component):
self._component = component
@abstractmethod
def operation(self):
pass
具体装饰器A(ConcreteDecoratorA)
class ConcreteDecoratorA(Decorator):
def operation(self):
return f"装饰器A增强了{self._component.operation()}"
具体装饰器B(ConcreteDecoratorB)
class ConcreteDecoratorB(Decorator):
def operation(self):
return f"装饰器B增强了{self._component.operation()}"
客户端代码
def clientCode(component: Component):
print(f"执行组件操作:{component.operation()}")
component = ConcreteDecoratorA(component)
print(f"执行装饰器A操作:{component.operation()}")
component = ConcreteDecoratorB(component)
print(f"执行装饰器B操作:{component.operation()}")
if __name__ == "__main__":
component = ConcreteComponent()
clientCode(component)
在这个示例中,我们有一个具体的组件ConcreteComponent
,它实现了一个operation
方法,然后我们有两个具体的装饰器ConcreteDecoratorA
和ConcreteDecoratorB
,它们也都实现了一个operation
方法,通过将这些装饰器应用于组件,我们可以在不修改组件结构的情况下为其添加新的行为。
装饰器模式是一种非常实用的设计模式,它可以帮助我们在不影响原有代码的基础上,轻松地为对象添加新的功能。