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

装饰器模式是一种结构型设计模式,用于动态地给对象添加额外的功能。它通过包装对象到装饰器类实例中实现这一点,避免了使用继承导致的类爆炸问题。文章提供了一个C++代码示例,展示了如何创建基础组件、具体组件、装饰器抽象类以及具体装饰器类。装饰器模式的优点在于运行时可扩展性,但缺点是可能导致更多的小类,增加代码维护难度。适合于需要在运行时动态添加行为的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值