#include <iostream>
using namespace std;
#define REQUEST1 1
#define REQUEST2 2
#define REQUEST3 3
/* ***********************************************************************
* 职责链模式
* 将请求传递到可以处理的类为止,子类中包含着处理的下一个对象指针
* 默认处理程序终结处理
* 在每个处理类中判定请求是不是可以处理,并且可以做一次预处理
* ***********************************************************************/
typedef struct _request {
int nType;
}Request;
class Handler;
class Handler {
public:
virtual void SetHandler(Handler* pHandler) =
0;
virtual int JudgeRequest(Request* pRequest) =
0;
virtual int HandleRequest(Request* pRequest) =
0;
protected:
Handler*
m_pHandler;
};
class Handler_1 :
public Handler {
public:
Handler_1() { }
~
Handler_1() { }
void SetHandler(Handler*
pHandler) {
m_pHandler =
pHandler;
}
int JudgeRequest(Request*
pRequest) {
if (pRequest->nType ==
REQUEST1)
return 1;
return 0;
}
int HandleRequest(Request*
pRequest) {
if (JudgeRequest(pRequest) >
0) {
printf("Handler_1\n");
return 0;
}
else {
m_pHandler->
HandleRequest(pRequest);
return 1;
}
}
};
class Handler_2 :
public Handler {
public:
Handler_2() { }
~
Handler_2() { }
void SetHandler(Handler*
pHandler) {
m_pHandler =
pHandler;
}
int JudgeRequest(Request*
pRequest) {
if (pRequest->nType ==
REQUEST2)
return 1;
return 0;
}
int HandleRequest(Request*
pRequest) {
if (JudgeRequest(pRequest) >
0) {
printf("Handler_2\n");
return 0;
}
else {
m_pHandler->
HandleRequest(pRequest);
return 1;
}
}
};
class Handler_3 :
public Handler {
public:
Handler_3() { }
~
Handler_3() { }
void SetHandler(Handler*
pHandler) {
m_pHandler =
pHandler;
}
int JudgeRequest(Request*
pRequest) {
if (pRequest->nType ==
REQUEST3)
return 1;
return 0;
}
int HandleRequest(Request*
pRequest) {
if (JudgeRequest(pRequest) >
0) {
printf("Handler_3\n");
return 0;
}
else {
m_pHandler->
HandleRequest(pRequest);
return 1;
}
}
};
void main()
{
Handler_1 h1;
Handler_2 h2;
Handler_3 h3;
h1.SetHandler(&
h2);
h2.SetHandler(&
h3);
Request r1;
r1.nType =
REQUEST1;
h1.HandleRequest(&
r1);
Request r2;
r2.nType =
REQUEST2;
h1.HandleRequest(&
r2);
Request r3;
r3.nType =
REQUEST3;
h1.HandleRequest(&
r3);
}
转载于:https://www.cnblogs.com/yanjiu/archive/2012/08/25/2656903.html
相关资源:数据结构—成绩单生成器