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

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

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

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

1.decorator模式与继承关系的目的都是要扩展对象的功能,但是decorator可以提供更多的灵活性

2。通过使用不同的具体装饰类以及这些装饰类的排列组合,设计师可以创造出很多不同行为的组合。

3)缺点

1.更多的复杂性

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

4)实现
cpp 复制代码
// 装饰器模式
// 时间: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;
}
相关推荐
小欣加油19 小时前
leetcode 面试题01.02判定是否互为字符重排
数据结构·c++·算法·leetcode·职场和发展
王璐WL20 小时前
【c++】c++第一课:命名空间
数据结构·c++·算法
aramae20 小时前
C++ -- 模板
开发语言·c++·笔记·其他
至此流年莫相忘21 小时前
设计模式:策略模式
设计模式·策略模式
MChine慕青1 天前
顺序表与单链表:核心原理与实战应用
linux·c语言·开发语言·数据结构·c++·算法·链表
ytadpole1 天前
揭秘设计模式:命令模式-告别混乱,打造优雅可扩展的代码
java·设计模式
骄傲的心别枯萎1 天前
RV1126 NO.16:通过多线程同时获取H264和H265码流
linux·c++·音视频·rv1126
落羽的落羽1 天前
【C++】特别的程序错误处理方式——异常机制
开发语言·c++
空山新雨(大队长)1 天前
C 语言第一课:hello word c
c++·c·exe
春蕾夏荷_7282977251 天前
c++ 第三方库与个人封装库
c++·三方库