网站建设的布局种类,免费一键生成logo网站,wordpress 小视频模板,东莞网站设计知名 乐云践新《设计模式》装饰者模式 
装饰者模式#xff08;Decorator Pattern#xff09;是一种结构型设计模式#xff0c;它允许在不改变现有对象结构的情况下#xff0c;动态地添加行为或责任到对象上。在装饰者模式中#xff0c;有一个抽象组件#xff08;Component#xff09;…《设计模式》装饰者模式 
装饰者模式Decorator Pattern是一种结构型设计模式它允许在不改变现有对象结构的情况下动态地添加行为或责任到对象上。在装饰者模式中有一个抽象组件Component接口定义了基本的操作具体组件Concrete Component是实现了这个接口的对象。装饰器Decorator实现了这个抽象组件的接口它持有一个指向组件对象的指针并定义了与组件接口一致的接口。同时装饰器可以在调用组件接口前或者后添加额外的行为或责任。具体装饰器Concrete Decorator是实现了装饰器接口的对象它可以包装一个具体组件或另一个装饰器。 
使用装饰者模式的主要优点包括 
在不改变现有对象结构的情况下可以动态地添加或删除行为或责任。可以使用多个装饰器对一个对象进行多次装饰以实现复杂的行为。装饰器与被装饰的对象可以独立变化互不影响。 
使用装饰者模式的一些常见场景包括 
当需要在不影响现有代码的情况下动态地给一个对象添加新的行为或责任时可以使用装饰者模式。当需要通过多次装饰来实现复杂的行为时可以使用装饰者模式。当需要在不影响其他对象的情况下对某个对象进行细粒度的控制时可以使用装饰者模式。 
装饰者模式的思想精髓在于它允许在运行时动态地添加行为而不需要通过继承来扩展对象的行为。在装饰者模式中所有的装饰器都遵循同一个接口这使得它们可以互相替换和组合从而实现非常灵活的行为扩展。同时由于装饰器模式不需要通过修改原有代码来添加新行为因此可以很好地遵循开放封闭原则使得代码更加可维护和可扩展。 
#include iostream
using namespace std;// 基础接口
class Component {
public:virtual void operation()  0;
};// 具体组件
class ConcreteComponent : public Component {
public:virtual void operation() {cout  具体组件的操作  endl;}
};// 装饰抽象类
class Decorator : public Component {
public:Decorator(Component* component) : m_pComponent(component) {}virtual void operation() {if (m_pComponent ! nullptr) {m_pComponent-operation();}}
protected:Component* m_pComponent;
};// 具体装饰类A
class ConcreteDecoratorA : public Decorator {
public:ConcreteDecoratorA(Component* component) : Decorator(component) {}virtual void operation() {Decorator::operation();addBehavior();}void addBehavior() {cout  具体装饰对象A的操作  endl;}
};// 具体装饰类B
class ConcreteDecoratorB : public Decorator {
public:ConcreteDecoratorB(Component* component) : Decorator(component) {}virtual void operation() {Decorator::operation();addBehavior();}void addBehavior() {cout  具体装饰对象B的操作  endl;}
};int main() {Component* component  new ConcreteComponent();ConcreteDecoratorA* decoratorA  new ConcreteDecoratorA(component);ConcreteDecoratorB* decoratorB  new ConcreteDecoratorB(decoratorA);decoratorB-operation();delete decoratorB;delete decoratorA;delete component;return 0;
}在这个示例中Component 定义了组件的基本接口ConcreteComponent 是具体的组件实现。Decorator 是装饰抽象类继承自 Component并持有一个 Component 对象。ConcreteDecoratorA 和 ConcreteDecoratorB 是具体的装饰类继承自 Decorator并在 operation 方法中先调用父类的 operation 方法再增加自己的行为。 
在 main 函数中我们首先创建了一个 ConcreteComponent 对象然后通过 ConcreteDecoratorA 和 ConcreteDecoratorB 对其进行装饰最终调用了 decoratorB 的 operation 方法来触发整个装饰过程。输出结果如下 
具体组件的操作
具体装饰对象A的操作
具体装饰对象B的操作