设计模式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. 装饰器模式会增加许多请求处理的复杂度。

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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值