📅  最后修改于: 2023-12-03 15:36:12.064000             🧑  作者: Mango
装饰模式是一种结构型设计模式,允许在运行时将行为添加到单个对象,而无需使用继承。它是一种替代继承的方案,具有更灵活的行为扩展方式。
适用场景包括:
装饰模式具有以下优点:
装饰模式具有以下缺点:
实现装饰模式的步骤如下:
以下是使用 Python 实现的装饰模式示例代码:
from abc import ABC, abstractmethod
class Component(ABC):
@abstractmethod
def operation(self):
pass
class ConcreteComponent(Component):
def operation(self):
return "ConcreteComponent"
class Decorator(Component):
def __init__(self, component):
self.component = component
def operation(self):
return self.component.operation()
class ConcreteDecoratorA(Decorator):
def __init__(self, component):
super().__init__(component)
self.added_state = "New state"
def operation(self):
return f"ConcreteDecoratorA({self.added_state})-{self.component.operation()}"
class ConcreteDecoratorB(Decorator):
def __init__(self, component):
super().__init__(component)
def new_behavior(self):
pass
def operation(self):
return f"ConcreteDecoratorB({self.new_behavior()})-{self.component.operation()}"
if __name__ == "__main__":
simple = ConcreteComponent()
print(simple.operation())
decorator_a = ConcreteDecoratorA(simple)
decorator_b = ConcreteDecoratorB(decorator_a)
print(decorator_b.operation())
代码中定义了基本组件接口 Component
和具体组件 ConcreteComponent
,在 ConcreteComponent
中实现了基础操作, Decorator
是基础装饰器基类, ConcreteDecoratorA
和 ConcreteDecoratorB
是基础装饰器子类,它们实现了 Decorator
中定义的接口,并在其上添加了行为,如状态和方法。在客户端代码中,使用原始对象和一些装饰器对象创建一个新对象,并调用其方法来体现装饰效果。