C++设计模式:责任链模式

一、源代码:

#include<iostream>
#include<memory>

using namespace std;

class AbstractLogger
{
public:
    static int _info;
    static int _debug;
    static int _error;

    void setNextLogger(shared_ptr<AbstractLogger> nextLogger)
    {
        this->_nextLogger = nextLogger;
    }
    void logMessage(int level,string message)
    {
        if(this->_level <= level)
        {
            write(message);
        }
        if(_nextLogger != nullptr)
        {
            _nextLogger->logMessage(level,message);
        }
    }
    virtual ~AbstractLogger() = default;
protected:
    int _level;
    //责任链中的下一个元素
    shared_ptr<AbstractLogger> _nextLogger;

    virtual void write(string message) = 0;
};

int AbstractLogger::_info = 1;
int AbstractLogger::_debug = 2;
int AbstractLogger::_error = 3;

class CongsoleLogger:public AbstractLogger
{
public:
    CongsoleLogger(int level)
    {
        this->_level = level;
    }
protected:
    virtual void write(string message) override
    {
        cout<<"Standard Console::Logger:"<<message<<endl;
    }
};

class ErrorLogger:public AbstractLogger
{
public:
    ErrorLogger(int level)
    {
        this->_level = level;
    }
protected:
    virtual void write(string message) override
    {
        cout<<"Error Console::Logger:"<<message<<endl;
    }
};

class FileLogger:public AbstractLogger
{
public:
    FileLogger(int level)
    {
        this->_level = level;
    }
protected:
    virtual void write(string message) override
    {
        cout<<"File::Logger:"<<message<<endl;
    }
};

int main()
{ 
    shared_ptr<AbstractLogger> errorLogger = make_shared<ErrorLogger>(AbstractLogger::_error);
    shared_ptr<AbstractLogger> fileLogger = make_shared<FileLogger>(AbstractLogger::_debug);
    shared_ptr<AbstractLogger> consoleLogger = make_shared<CongsoleLogger>(AbstractLogger::_info);

    errorLogger->setNextLogger(fileLogger);
    fileLogger->setNextLogger(consoleLogger);
    consoleLogger->setNextLogger(nullptr);

    errorLogger->logMessage(AbstractLogger::_info,"This is an information.");
    cout<<endl;
    errorLogger->logMessage(AbstractLogger::_debug,"This is an debug level information.");
    cout<<endl;
    errorLogger->logMessage(AbstractLogger::_error,"This is an error information.");
}

二、运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值