責任鏈模式(Chain of Responsibility)的目標是使多個對象都有機會處理請求,從而避免請求的發送者和接收者之間的耦合關係。將這些對象連成一條鏈,並沿着這條鏈傳遞請求,直到有一個對象處理它爲止。ios
舉個例子。你到銀行去辦理業務,只是簡單的存個錢,也許ATM就解決你的問題。若是你是爲了交費用的,那等去櫃檯,但你倒是來諮詢金融產品的,會有專員接待你,事實上你是一個大客戶,經理就會把你請到他辦公室好好和你談談,就這樣。spa
類圖的關係以下:code
代碼實現:對象
#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"get
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"it
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_Hio
#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"class
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;
}
注:在此處只是以業務錢數的大小來分類,並且經理很牛,能解決一切問題,因此不會使請求得不到解決。