1. 职责链模式:使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这个对象连成一条链,并且沿着这条链传递该请求,直到有一个对象处理它为止;
2. 应用场景:给系统降低了耦合性,请求的发送者完全不必知道该请求会被哪个应答对象处理;
3. 结构图
// 定义一个处理请示的接口;
class Handler
{
public:
Handler(void);
virtual ~Handler(void);
void SetSuccessor(Handler *pHandler) // 设置继任者
{
m_pHandler = pHandler;
}
// 处理请求的抽象方法;
virtual void HandleRequest(int iReauest) = 0;
protected:
Handler *m_pHandler;
};
// 具体处理者类
class ConcreteHandler1 : public Handler
{
public:
ConcreteHandler1(void);
~ConcreteHandler1(void);
void HandleRequest(int iRequest)
{
if (iRequest >= 0 && iRequest < 10)
{
cout<<"h1处理请求"<<iRequest<<endl;
}
else if (m_pHandler != NULL) // 转移到下一位;
{
m_pHandler->HandleRequest(iRequest);
}
}
};
// 具体处理者类
class ConcreteHandler2 : public Handler
{
public:
ConcreteHandler2(void);
~ConcreteHandler2(void);
void HandleRequest(int iRequest)
{
// 符合条件,处理请求;
if (iRequest >= 10 && iRequest < 20)
{
cout<<"h2处理请求"<<iRequest<<endl;
}
else if (m_pHandler != NULL) // 转移到下一位;
{
m_pHandler->HandleRequest(iRequest);
}
}
};
// 客户端代码:
#include "ConcreteHandler1.h"
#include "ConcreteHandler2.h"
#include "ConcreteHandler3.h"
// 职责链模式:使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这个对象连成一条链,并且沿着这条链传递该请求,直到有一个
// 对象处理它为止;[8/14/2016 ZOSH];
int _tmain(int argc, _TCHAR* argv[])
{
Handler *pH1 = new ConcreteHandler1;
Handler *pH2 = new ConcreteHandler2;
Handler *pH3 = new ConcreteHandler3;
pH1->SetSuccessor(pH2); // 设置职责链的下家;
pH2->SetSuccessor(pH3);
int iRequests[] = {2, 5, 14, 22, 18, 3, 27, 20};
for each (int i in iRequests) // 遍历请求命令;
{
pH1->HandleRequest(i);
}
// 清除指针与内存;
if (pH1)
{
delete pH1;
pH1 = NULL;
}
if (pH2)
{
delete pH2;
pH2 = NULL;
}
if (pH3)
{
delete pH3;
pH3 = NULL;
}
return 0;
}