责任链模式:
Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.(使多个对象都有机会处理请求,从而避免了请求的发送者和接受者之间的耦合关系。将这些对象连成一条链,并沿着这条链条传递该请求,直到有对象处理它为止
C++实现:
#ifndef __CHAIN_OF_RESPONSIBILTY_H__
#define __CHAIN_OF_RESPONSIBILTY_H__
#include <iostream>
using namespace std;
class ChainHandle {
public:
ChainHandle() : _succ(0) { }
virtual ~ChainHandle() { delete _succ; }
virtual void HandleRequest() = 0;
void SetSuccessor(ChainHandle* pSucc) { _succ = pSucc; }
ChainHandle* GetHandle() { return _succ; }
private:
ChainHandle* _succ;
};
class ConcreteHandleA : public ChainHandle {
public:
void HandleRequest() {
if (this->GetHandle() != NULL) {
cout << "ConcreteHandleA 把责任转交给后继结点处理" << endl;
this->GetHandle()->HandleRequest();
} else {
cout << "ConcreteHandleA 没有后继,必须自己处理" << endl;
}
}
};
class ConcreteHandleB : public ChainHandle {
public:
void HandleRequest() {
if (this->GetHandle() != NULL) {
cout << "ConcreteHandleB 把责任转交给后继结点处理" << endl;
this->GetHandle()->HandleRequest();
} else {
cout << "ConcreteHandleB 没有后继,必须自己处理" << endl;
}
}
};
#endif
#include "ChainOfResponsibility.h"
int main()
{
ChainHandle* h1 = new ConcreteHandleA();
ChainHandle* h2 = new ConcreteHandleB();
h1->SetSuccessor(h2);
h1->HandleRequest();
return 0;
}
Chain of Responsibility 模式的最大的优点就是给系统降低了耦合性,请求的发送者完全不必知道该请求会被哪个应答对象处理,极大地降低了系统的耦合性。
缺点:1,性能问题:每次都是从链头遍历。2,调试困难,当环节较多的时候,调试的逻辑变得复杂。