责任链表的本质是:将可能处理一个请求的对象链接成一个链,并将请求在这个链上传递,直到有对象处理该请求(可能需要提供一个默认处理所有请求的类)
UML结构图:
这个模式也比较简单,没太多值得说得,复制了这里的内容:http://blog.csdn.net/lcl_data/article/details/9042739
辛辛苦苦了工作了一年,终于可以加薪了,向主管提交了加薪申请,主管一看不得了,自己职权不够,批不了,主管把申请上交总监,总监发现自己也批不了,申请到了总经理手中,总经理一看,小伙子口气不小了,有胆识敢申请,先来谈下心。
#include <iostream>
#include <string>
using namespace std;
// 请求
class Request
{
public:
int m_nNumber;
};
// 管理者
class Manager
{
public:
Manager(string temp) { name = temp; }
void SetSuccessor(Manager* temp) { manager = temp; }
virtual void GetRequest(Request* request) = 0;
virtual ~Manager() {}
protected:
Manager* manager;
string name;
};
// 经理
class CommonManager : public Manager
{
public:
CommonManager(string strTemp) : Manager(strTemp) {}
virtual void GetRequest(Request* request);
~CommonManager() final {};
};
void CommonManager::GetRequest(Request* request)
{
if (request->m_nNumber>=0 && request->m_nNumber<1000)
{
cout << name << " 处理了请求: " << request->m_nNumber << endl;
}
else
{
manager->GetRequest(request);
}
}
// 总监
class Majordomo : public Manager
{
public:
Majordomo(string strTemp) : Manager(strTemp) {}
virtual void GetRequest(Request* request);
};
void Majordomo::GetRequest(Request* request)
{
if (request->m_nNumber <= 5000)
{
cout << name << " 处理了请求: " << request->m_nNumber << endl;
}else
{
manager->GetRequest(request);
}
}
//总经理
class GeneralManager: public Manager
{
public:
GeneralManager(string name):Manager(name) {}
virtual void GetRequest(Request* request) //总经理可以处理所有请求
{
cout << name << " 处理了请求: " << request->m_nNumber << endl;
}
};
int main(){
Manager* common = new CommonManager("张经理");
Manager* major = new Majordomo("李总监");
GeneralManager* general = new GeneralManager("赵总");
common->SetSuccessor(major);
major->SetSuccessor(general);
Request* rq = new Request();
rq->m_nNumber = 999;
common->GetRequest(rq);
rq->m_nNumber = 4999;
common->GetRequest(rq);
rq->m_nNumber = 6999;
common->GetRequest(rq);
delete rq;
delete major;
delete common;
delete general;
return 0;
}