版权声明:本文为博主原创文章,未经博主允许不得转载。
- /*
- 职责链模式:避免请求发送者和接受者耦合在一起,让多个对象都有机会处理请求,将这些对象连接处一条链,并且
- 沿着这条链传递请求,直到有对象处理它为止。
- 在以下情况下可以使用职责链模式:
- (1)有多个对象可以处理同一个请求,具体哪个对象处理该请求由运行时刻自动确定。
- (2)在不明确指定接收者的情况下,向多个对象中的一个提交一个请求。
- (3)可动态指定一组对象处理请求。
- 应用举例:
- 可以用于避免多个if..else分支结构
- Created by Phoenix_FuliMa
- */
- #include<iostream>
- using namespace std;
- class Handler
- {
- protected:
- Handler *_successor;
- public:
- virtual void Handle(int value) = 0;
- void SetSuccessor(Handler *successor)
- {
- this->_successor = successor;
- }
- };
- class Handler_level_1: public Handler
- {
- public:
- virtual void Handle(int value)
- {
- if(value == 1)
- {
- cout<<"Handler_level_1 can handle"<<endl;
- }
- else
- {
- cout<<"Handler_level_1 can't handle"<<endl;
- this->_successor->Handle(value);
- }
- }
- };
- class Handler_level_2: public Handler
- {
- public:
- void Handle(int value)
- {
- if(value == 2)
- {
- cout<<"Handler_level_2 can handle"<<endl;
- }
- else
- {
- cout<<"Handler_level_2 can't handle"<<endl;
- _successor->Handle(value);
- }
- }
- };
- class Handler_level_end:public Handler
- {
- public:
- void Handle(int value)
- {
- if(value == 3)
- {
- cout<<"Handler_level_3 can handle"<<endl;
- }
- else
- {
- cout<<"No Handler can handle this value"<<endl;
- }
- }
- };
- int main()
- {
- Handler_level_1 *handle_1 = new Handler_level_1();
- Handler_level_2 *handle_2 = new Handler_level_2();
- Handler_level_end * handle_end = new Handler_level_end();
- handle_1->SetSuccessor(handle_2);
- handle_2->SetSuccessor(handle_end);
- handle_end->SetSuccessor(NULL);
- handle_1->Handle(1);
- cout<<endl;
- handle_1->Handle(2);
- cout<<endl;
- handle_1->Handle(3);
- cout<<endl;
- handle_1->Handle(4);
- cout<<endl;
- delete handle_1;
- delete handle_2;
- delete handle_end;
- system("pause");
- return 0;
- }
![](https://img-my.csdn.net/uploads/201211/18/1353200263_1576.png)