设计模式9之c++装饰器模式(含示例代码)

装饰器模式(Decorator Pattern)是一种结构型设计模式。它允许你通过将对象包装在一个装饰器类的实例中来动态地修改对象的行为。

下面是一个使用装饰器模式的C++代码示例:

#include <iostream>
using namespace std;

// 基础组件接口类
class Component {
public:
    virtual void operation() = 0;
};

// 具体组件类
class ConcreteComponent : public Component {
public:
    virtual void operation() override {
        cout << "ConcreteComponent operation." << endl;
    }
};

// 装饰器抽象类
class Decorator : public Component {
public:
    Decorator(Component* component) : component_(component) {}
    virtual void operation() override {
        if (component_) {
            component_->operation();
        }
    }

protected:
    Component* component_;
};

// 具体装饰器类A
class ConcreteDecoratorA : public Decorator {
public:
    ConcreteDecoratorA(Component* component) : Decorator(component) {}
    virtual void operation() override {
        Decorator::operation();
        cout << "ConcreteDecoratorA operation." << endl;
    }
};

// 具体装饰器类B
class ConcreteDecoratorB : public Decorator {
public:
    ConcreteDecoratorB(Component* component) : Decorator(component) {}
    virtual void operation() override {
        Decorator::operation();
        cout << "ConcreteDecoratorB operation." << endl;
    }
};

int main() {
    Component* component = new ConcreteComponent();
    Decorator* decoratorA = new ConcreteDecoratorA(component);
    Decorator* decoratorB = new ConcreteDecoratorB(decoratorA);

    decoratorB->operation();

    delete component;
    delete decoratorA;
    delete decoratorB;

    return 0;
}

优点:

  1. 装饰器模式使得添加新功能变得方便。

  2. 装饰器模式避免了使用继承扩展对象功能时带来的类爆炸问题。

  3. 装饰器模式允许你在运行时动态地向对象添加功能,而不是在编译时就确定好。

缺点:

  1. 使用装饰器模式会增加许多小类,可能会导致代码比较难以维护。

  2. 装饰器模式会增加许多请求处理的复杂度。

装饰器模式适合于需要在运行时动态地为对象添加新的行为时使用。

猜你喜欢

转载自blog.csdn.net/dica54dica/article/details/129744594