*****************************在上看到一篇责任链的文章,用c++给他重写一遍自己也学习下。
*****************************
class Handler {
protected:
Handler *successor;
public:
void SetSuccessor(Handler *suc) {
successor = suc;
}
virtual void HandleRequest(int request) = 0;
};class Concretehandler1 :public Handler {
public:
void HandleRequest(int request) {
if (request > 0 && request < 20) {
cout << "do 1" << endl;
} else if (successor != NULL) {
successor->HandleRequest(request);
}
}
};class Concretehandler2 :public Handler {
public:
void HandleRequest(int request) {
if (request > 20) {
cout << "do 2" << endl;
} else if (successor != NULL) {
successor->HandleRequest(request);
}
}
};int _tmain(int argc, _TCHAR* argv[])
{
Handler *h1 = new Concretehandler1;
Handler *h2 = new Concretehandler2;
Handler *h22 = new Concretehandler2;h1->SetSuccessor(h2);
h2->SetSuccessor(h22);
h22->SetSuccessor(NULL);int requests[] = {23,2,3};
for (int i = 0;i < 3;i++) {
h1->HandleRequest(requests[i]);
cout << "**********" << endl;
}
system("pause");
}
*****************************
write by fgd