C++设计模式——22装饰器模式

装饰器模式是一种设计模式,用于在不修改原有对象的情况下动态添加额外职责。相比于继承,它提供了更灵活的扩展性。本文通过示例展示了如何在C++中实现装饰器模式,包括Component、ConcreteComponent、Decorator和ConcreteDecorator的定义,以及如何在客户端代码中使用它们来扩展和撤销对象功能。

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

装饰器模式

装饰器模式(Decorator),动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。

主要作用

动态地给一个对象添加一些额外的职责。就增加功能来说,装饰器模式相比生成子类更为灵活。

解决的问题

一般的,我们为了扩展一个类经常使用继承方式实现,由于继承为类引入静态特征,并且随着扩展功能的增多,子类会很膨胀。

使用场景

  1. 扩展一个类的功能。
  2. 动态增加功能,动态撤销。

实现

在这里插入图片描述
Component是定义一个对象接口,可以给这些对象动态地添加职责。ConcreteComponent是定义了一个具体的对象,也可以给这个对象添加一些职责。Decorator,装饰抽象类,继承了Component,从外来扩展Component类的功能,但对于Component来说,是无需知道Decorator的存在的。至于ConcreteDecorator就是具体的装饰对象,起到给Component添加职责的功能。
Component类

class Component
{
public: 
    virtual void Operation() = 0;
};

Concrete Component类

class ConcreteComponent : public Component
{
public:
    void Operation() override
    {
        cout<<"具体对象操作"<<endl;
    }

};

Decorator类

class Decorator : public Component
{
protected:
    Component * component;

public:
    void SetComponent(Component * component)
    {
        this->component = component;
    }

    void Operation() override
    {
        if (component != nullptr)
        {
            component->Operation();
        }
    }

};

ConcreteDecoratorA类

class ConcreteDecoratorA : public Decorator
{
private:
    string addedState;

public:
    void Operation() override
    {
        Decorator::Operation();
        addedState = "New State";
        cout<<"具体装饰对象A的操作"<<endl;
    }
};

class ConcreteDecoratorB : public Decorator
{
public:
    void Operation() override
    {
        Decorator::Operation();
        AddedBehavior();
        cout<<"具体装饰对象B的操作"<<endl;
    }

private:
    void AddedBehavior()
    {

    }
};

客户端代码

int main()
{
    ConcreteComponent * c = new ConcreteComponent();
    ConcreteDecoratorA * d1 = new ConcreteDecoratorA();
    ConcreteDecoratorB * d2 = new ConcreteDecoratorB();

    d1->SetComponent(c);
    d2->SetComponent(d1);
    d2->Operation();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值