Chain of Responsibility模式
熟悉MFC的朋友都知道,MFC是"基于消息,事件驱动" 滴,它的向上传递消息的机制跟职责链的思想是相同的,其实Qt中的
touchEvent也是这样处理的。
职责链模式的最大一个优点就是降低了系统的耦合性,请求的发送者完全不知道该请求会被哪个应答对象处理。
C++代码示例:
<strong>//Handle.h</strong>
#ifndef _HANDLE_H_
#define _HANDLE_H_
class Handle
{
public:
virtual ~Handle();
virtual void HandleRequest() = 0;
void SetSuccessor(Handle* succ);
Handle* GetSuccessor();
protected:
Handle();
Handle(Handle* succ);
private:
Handle* _succ;
};
class ConcreteHandleA:public Handle
{
public:
ConcreteHandleA();
~ConcreteHandleA();
ConcreteHandleA(Handle* succ);
void HandleRequest();
};
class ConcreteHandleB:public Handle
{
public:
ConcreteHandleB();
~ConcreteHandleB();
ConcreteHandleB(Handle* succ);
void HandleRequest();
};
#endif //~_HANDLE_H_
<strong>//Handle.cpp</strong>
#include "Handle.h"
#include <iostream>
using namespace std;
Handle::Handle()
{
_succ = 0;
}
Handle::~Handle()
{
delete _succ;
}
Handle::Handle(Handle* succ)
{
this->_succ = succ;
}
void Handle::SetSuccessor(Handle* succ)
{
_succ = succ;
}
Handle* Handle::GetSuccessor()
{
return _succ;
}
void Handle::HandleRequest()
{
}
ConcreteHandleA::ConcreteHandleA()
{
}
ConcreteHandleA::ConcreteHandleA(Handle*succ):Handle(succ){
}
ConcreteHandleA::~ConcreteHandleA()
{
}
void ConcreteHandleA::HandleRequest()
{
if (this->GetSuccessor() != 0)
{
cout<<"ConcreteHandleA 我把处理权给后继节点....."<<endl;
this->GetSuccessor()->HandleRequest();
}
else
{
cout<<"ConcreteHandleA 没有后继了,我必须自己处理...."<<endl;
}
}
ConcreteHandleB::ConcreteHandleB(){
}
ConcreteHandleB::ConcreteHandleB(Handle*succ):Handle(succ){
}
ConcreteHandleB::~ConcreteHandleB(){
}
void ConcreteHandleB::HandleRequest(){
if (this->GetSuccessor() != 0)
{
cout<<"ConcreteHandleB 我把处理权给后继节点....."<<endl;
this->GetSuccessor()->HandleRequest();
}
else
{
cout<<"ConcreteHandleB 没有后继了,我必须自己处理...."<<endl;
}
}
<strong>//main.cpp</strong>
#include "Handle.h"
#include <iostream>
using namespace std;
int main(int argc,char* argv[])
{
Handle* h1 = new ConcreteHandleA();
Handle* h2 = new ConcreteHandleB();
h1->SetSuccessor(h2);
h1->HandleRequest();
return 0;
}