设计模式-责任链模式

学习笔记:责任链模式
模式简介

:属于行为型模式,对请求的发送者和接受者解耦。

为什么用

:对于一个需求,可能有很多对象可以接受处理,一旦某个对象无法处理,就把请求传给更高级的对象。

怎么样用

:处理请求的对象实现统一的接口,每个对象内有指向下一级处理对象的指针,根据处理等级来决定请求的处理对象。

注意事项

:严格按处理等级来,避免循环嵌套。

实际举例

:游戏控制台信息打印

#include<iostream>
using namespace std;
class Log {
public:
	enum class Level {
		verbose,//琐碎文本 
		debug,//调试文本
		info,//重要文本
		warning,//警告文本 
		error//错误文本
	};
protected:
	Level level;
	Log *nextLog;
public:
	void handleLog(Level _level,string message) {
		if (level >= _level) {
			log(message);
		}
		else {
			if (nextLog != NULL) {
				nextLog->handleLog(_level, message);
			}
		}
	}
protected:
	virtual void log(string message) {
		cout << "待实现的方法\n";
	}
};
class Log_Verbose :public Log {
public:
	Log_Verbose(Log *log ) {
		this->nextLog = log;
		this->level = Level::verbose;
	}
	void log(string message) {
		cout << "verbose: " + message << "\n";
	}
};
class Log_Debug :public Log {
public:
	Log_Debug(Log* log) {
		this->nextLog = log;
		this->level = Level::debug;
	}
	void log(string message) {
		cout << "debug: " + message << "\n";
	}
};
class Log_Info :public Log {
public:
	Log_Info(Log* log) {
		this->nextLog = log;
		this->level = Level::info;
	}
	void log(string message) {
		cout << "info: " + message << "\n";
	}
};
class Log_Warning :public Log {
public:
	Log_Warning(Log* log) {
		this->nextLog = log;
		this->level = Level::warning;
	}
	void log(string message) {
		cout << "warning: " + message << "\n";
	}
};
class Log_Error :public Log {
public:
	Log_Error() {
		this->level = Level::error;
	}
	void log(string message) {
		cout << "error: " + message << "\n";
	}
};
int main()
{
	Log_Error* log_error = new Log_Error();
	Log_Warning* log_warning = new Log_Warning(log_error);
	Log_Info* log_info = new Log_Info(log_warning);
	Log_Debug* log_debug = new Log_Debug(log_info);
	Log_Verbose* log_verbose = new Log_Verbose(log_debug);
	log_verbose->handleLog(Log::Level::info,"这是一个重要的操作");
	log_verbose->handleLog(Log::Level::error, "非法访问游戏属性");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值