一、源代码:
#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.");
}
二、运行结果: