装饰器模式是一种结构型设计模式,它允许向对象动态地添加新功能,同时不改变其结构。这种模式是通过创建一个包装类,包装原始类的实例,来实现的。

装饰器模式包含以下几个主要角色:

1. 组件接口(Component): 定义了具体组件和装饰器共同的接口。
2. 具体组件(Concrete Component): 实现了组件接口,是被装饰的原始对象。
3. 装饰器(Decorator): 继承自组件接口,包含一个指向具体组件的引用,并定义了与组件接口一致的接口。
4. 具体装饰器(Concrete Decorator): 扩展了装饰器,负责具体的装饰逻辑。

以下是一个简单的 Python 示例,演示了装饰器模式用于动态添加日志功能:
from abc import ABC, abstractmethod

# 组件接口
class Component(ABC):
    @abstractmethod
    def operation(self):
        pass

# 具体组件
class ConcreteComponent(Component):
    def operation(self):
        return "Concrete Component"

# 装饰器
class Decorator(Component):
    def __init__(self, component):
        self.component = component

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

# 具体装饰器:添加日志功能
class LoggingDecorator(Decorator):
    def operation(self):
        result = super().operation()
        return f"{result} + Logging"

# 具体装饰器:添加时间戳功能
class TimestampDecorator(Decorator):
    def operation(self):
        result = super().operation()
        return f"{result} + Timestamp"

# 客户端
component = ConcreteComponent()
decorator1 = LoggingDecorator(component)
decorator2 = TimestampDecorator(decorator1)

result = decorator2.operation()
print(result)  # 输出 "Concrete Component + Logging + Timestamp"

在这个示例中,Component 是组件接口,ConcreteComponent 是具体组件,它实现了组件接口。Decorator 是装饰器,它包含一个指向具体组件的引用,并实现了组件接口。LoggingDecorator 和 TimestampDecorator 是具体装饰器,它们分别扩展了装饰器,添加了日志和时间戳功能。

客户端可以选择在运行时动态地组合这些装饰器,以实现不同的功能组合,而无需修改原始组件的代码。

装饰器模式广泛应用于需要动态地扩展对象功能的场景,例如在不修改现有类的情况下,给对象添加新的行为。


转载请注明出处:http://www.zyzy.cn/article/detail/13946/设计模式