装饰模式(Decorator Pattern)是一种结构型设计模式。它能在不改变原有对象的结构的基础上,添加新的行为或责任。装饰模式以对象组合的方式实现这一功能,而不是通过继承。
角色:
- 组件(Component): 定义一个抽象接口,是被装饰对象和装饰对象的共同接口。
- 具体组件(Concrete Component): 实现组件的具体功能,是被装饰的对象。
- 装饰器(Decorator): 持有一个指向组件的引用,并实现组件的抽象接口。装饰器可以附加额外的责任。
- 具体装饰器(Concrete Decorator): 实现装饰器接口,具体定义要添加到组件的新功能。可以有多个具体装饰器,它们可以以灵活的方式组合使用。
类图
![2024-01-22T10:53:57.png][1]
代码示例
```c++
include
// 组件接口 class Component { public: virtual void operation() const = 0; };
// 具体组件 class ConcreteComponent : public Component { public: void operation() const override { std::cout << "Concrete Component operation." << std::endl; } };
- // 装饰器
- class Decorator : public Component {
- public:
- Decorator(Component* component)
component(component) {}
void operation() const override { if (component) { component->operation(); } }
protected: Component* component; };
- // 具体装饰器A
- class ConcreteDecoratorA : public Decorator {
- public:
- ConcreteDecoratorA(Component* component)
Decorator(component) {}
void operation() const override { Decorator::operation(); addAdditionalFunctionality(); }
void addAdditionalFunctionality() const { std::cout << "Concrete Decorator A adds additional functionality." << std::endl; } };
- // 具体装饰器B
- class ConcreteDecoratorB : public Decorator {
- public:
- ConcreteDecoratorB(Component* component)
Decorator(component) {}
void operation() const override { Decorator::operation(); addAdditionalFunctionality(); }
void addAdditionalFunctionality() const { std::cout << "Concrete Decorator B adds additional functionality." << std::endl; } };
int main() { // 创建具体组件 ConcreteComponent concreteComponent;
// 创建具体装饰器A,传入具体组件
ConcreteDecoratorA decoratorA(&concreteComponent);
// 创建具体装饰器B,传入具体装饰器A
ConcreteDecoratorB decoratorB(&decoratorA);
// 调用操作,依次执行组件和各个装饰器的功能
decoratorB.operation();
return 0;
}
[1]: https://lcslearn.top/usr/uploads/2024/01/3152299099.png