1.Chain of Responsibility模式:将可能处理一个请求的对象链接成一个链,并将请求在这个链上传递,直到有对象处理该请求(可能需要提供一个默认处理所有请求的类,例如MFC中的CwinApp类)。

2.Chain of Responsibility Pattern 结构图

Chain of Responsibility Pattern-LMLPHP

3.实现

 #ifndef _HANDLE_H_
#define _HANDLE_H_ class Handle
{
public:
virtual ~Handle();
virtual void HandleRequest() = ;
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(); protected:
private:
}; class ConcreteHandleB:public Handle
{
public:
ConcreteHandleB();
~ConcreteHandleB();
ConcreteHandleB(Handle* succ);
void HandleRequest();
protected:
private:
}; #endif

Handle.h

 #include "Handle.h"
#include <iostream>
using namespace std; Handle::Handle()
{
_succ = ;
}
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() != )
{
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() != )
{
cout<<"ConcreteHandleB 我把处理权给后继节点....."<<endl;
this->GetSuccessor()->HandleRequest();
}
else
{
cout<<"ConcreteHandleB 没有后继了,我必须自己处理...."<<endl;
}
}

Handle.cpp

 #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 ;
}

main.cpp

05-11 22:19