装饰模式C++实现

本文通过C++实现装饰模式,展示了其灵活性和组合性。通过具体代码实例,说明了如何通过装饰器类来扩展核心业务的功能,实现了check-log-operation和log-check-operation的不同组合。

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

今天学习了下装饰模式,亲自用C++实现了下,感觉最大的好处在于各个装饰器可以灵活的组合。UML图如下:

代码实现如下:

/*
测试装饰模式实现方法
*/
#include <iostream>
#include <string>
using namespace std;

/*
基类接口
*/
class Component
{
public:
    virtual void operation(const string& msg) = 0;
};

/*
核心业务
*/
class ConcreteComponent : public Component
{
public:
    void operation(const string& msg)
    {
        cout << "I am contrete work." << endl;
        return;
    }
};

/*
装饰器基类
*/
class Decorator : public Component
{
private:
    Component* com;
public:
    Decorator(Component* c):com(c){}

public:
    void operation(const string& msg)
    {
        com->operation(msg);
    }
};


/*
实际装饰类
*/
class Checker : public Decorator
{
public:
    Checker(Component* c): Decorator(c){}

public:
    void operation(const string& msg)
    {
        cout << "do check operations..." << endl;
        Decorator::operation(msg);
    }
};

/*
实际装饰类
*/
class Logger : public Decorator
{
public:
    Logger(Component* c) : Decorator(c){}

public:
    void operation(const string & msg)
    {
        cout << "do loggs..." << endl;
        Decorator::operation(msg);
    }
};


int main(int argc, char** argv)
{
    /*
    将不同的装饰类灵活的组合在一起,形成不同的功能
    check-log-operation组合
    */
    Component* op = new Checker(new Logger(new ConcreteComponent()));
    op->operation("This is a test!");

    cout << endl;

    /*
    log-check-operation组合
    */
    Component* op1 = new Logger(new Checker(new ConcreteComponent()));
    op1->operation("This is a test 2!");
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值