【设计模式之装饰器模式 -- C++】

本文详细介绍了装饰器模式,强调了其在不改变原类和避免继承的情况下扩展对象功能的灵活性,同时讨论了其优点(如提供更多灵活性)、缺点(如增加复杂性)和实现方式,通过代码示例展示了如何使用装饰器模式组合行为。
摘要由CSDN通过智能技术生成

7.装饰器模式 – 包装对象,增强功能

装饰模式指的是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。百度百科

1)设计原则 – 抽象父类,子类实现
  1. 多组合,少继承。
    利用继承设计子类的行为,是在编译时静态决定的,而且所有的子类都会继承到相同的行为。然而,如果能够利用组合的做法扩展对象的行为,就可以在运行时动态地进行扩展。
  2. 类应设计的对扩展开放,对修改关闭。
2)优点

1.decorator模式与继承关系的目的都是要扩展对象的功能,但是decorator可以提供更多的灵活性
2。通过使用不同的具体装饰类以及这些装饰类的排列组合,设计师可以创造出很多不同行为的组合。

3)缺点

1.更多的复杂性
2.设计中会出现很多小类,过度使用,会使程序更复杂。

4)实现
// 装饰器模式
// 时间:2024-2-1
// 作者:@conceal
#include <iostream>
#include <string>
using namespace std;

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

class ConcreteComponent : public Component
{
public:
    void Operation()
    {
        cout << "ConcreteComponent operation..." << endl;
    }
};

class Decorator : public Component
{
public:
    Decorator(Component* component) : m_component(component) {}
    void Operation()
    {
        m_component->Operation();
    }
private:
    Component* m_component;
};

class ConcreteDecoratorA : public Decorator
{
public:
    ConcreteDecoratorA(Component* component) : Decorator(component) {}
    void Operation()
    {
        Decorator::Operation();
        AddedBehavior();
        cout << "ConcreteDecoratorA operation..." << endl;
    }
    void AddedBehavior()
    {
        cout << "ConcreteDecoratorA added behavior..." << endl;
    }
};

class ConcreteDecoratorB : public Decorator
{
public:
    ConcreteDecoratorB(Component* component) : Decorator(component) {}
    void Operation()
    {
        Decorator::Operation();
        AddedBehavior();
        cout << "ConcreteDecoratorB operation..." << endl;
    }
    void AddedBehavior()
    {
        cout << "ConcreteDecoratorB added behavior..." << endl;
    }
};

int main()
{
    Component* component = new ConcreteComponent();
    Decorator* decoratorA = new ConcreteDecoratorA(component);
    Decorator* decoratorB = new ConcreteDecoratorB(decoratorA);
    decoratorB->Operation();
    delete decoratorB;
    delete decoratorA;
    delete component;
    return 0;
}

  • 13
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值