责任链模式(Chain of Responsibility)的目标是使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递请求,直到有一个对象处理它为止。
举个例子。你到银行去办理业务,只是简单的存个钱,也许ATM就解决你的问题。如果你是为了交费用的,那等去柜台,但你却是来咨询金融产品的,会有专员接待你,事实上你是一个大客户,经理就会把你请到他办公室好好和你谈谈,就这样。
类图的关系如下:
代码实现:
#ifndef BANKWORKER_H
#define BANKWORKER_H
#include <iostream>
using namespace std;
class BankWorker
{
public:
BankWorker(int _standard, BankWorker *_pNext);
virtual ~BankWorker();
virtual void handle(int) = 0;
protected:
int getStandard() const {return standard;}
BankWorker* getNextWorker() const {return p_nextWorker;}
private:
int standard;
BankWorker *p_nextWorker;
};
#endif // BANKWORKER_H
#include "bankworker.h"
BankWorker::BankWorker(int _standard, BankWorker *_pNext):standard(_standard)
,p_nextWorker(_pNext)
{
}
BankWorker::~BankWorker()
{
delete p_nextWorker;
cout << "~~~\n";//能够帮助你了解析构的过称,更好的掌握继承
}
#ifndef ATM_H
#define ATM_H
#include "bankworker.h"
class ATM : public BankWorker
{
public:
ATM(int _s,BankWorker *_p);
~ATM(){cout <<"ATM\n";}
void handle(int client);
};
#endif // ATM_H
#include "atm.h"
ATM::ATM(int _s, BankWorker *_p):BankWorker(_s,_p)
{
}
void ATM::handle(int client)
{
if (getStandard() > client) {
cout << "ATM fall for you!\n";
}
else {
if (getNextWorker() != NULL) {
getNextWorker()->handle(client);
}
}
}
#ifndef COUNTERBOY_H
#define COUNTERBOY_H
#include "bankworker.h"
class Counterboy : public BankWorker
{
public:
Counterboy(int _s,BankWorker *_p);
~Counterboy(){cout << "Counterboy\n";}
void handle(int client);
};
#endif // COUNTERBOY_H
#include "counterboy.h"
Counterboy::Counterboy(int _s, BankWorker *_p):BankWorker(_s, _p)
{
}
void Counterboy::handle(int client)
{
if (getStandard() > client) {
cout << "Counterboy fall for you!";
}
else {
if (getNextWorker() != NULL) {
getNextWorker()->handle(client);
}
}
}
#ifndef MANAGER_H
#define MANAGER_H
#include "bankworker.h"
class Manager : public BankWorker
{
public:
Manager(int _s = 0,BankWorker *_p = NULL);
~Manager(){cout << "manager\n";}
void handle(int client);
};
#endif // MANAGER_H
#include "manager.h"
Manager::Manager(int _s, BankWorker *_p):BankWorker(_s, _p)
{
}
void Manager::handle(int client)
{
cout << "I am Manager, I can do anything for you!" << '\n';
}
#include <iostream>
using namespace std;
#include "atm.h"
#include "counterboy.h"
#include "manager.h"
int main()
{
Manager *p_m = new Manager();
Counterboy *p_c = new Counterboy(10000,p_m);
ATM *p_atm = new ATM(2000,p_c);
p_atm->handle(30000);
delete p_atm;
return 0;
}
注:在此处只是以业务钱数的大小来分类,而且经理很牛,能解决一切问题,所以不会使请求得不到解决。