Chain of Responsibility Pattern

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

2.Chain of Responsibility Pattern 结构图

3.实现

 1 #ifndef _HANDLE_H_ 
 2 #define _HANDLE_H_
 3 
 4 class Handle 
 5 { 
 6 public: 
 7     virtual ~Handle();
 8     virtual void HandleRequest() = 0;
 9     void SetSuccessor(Handle* succ);
10     Handle* GetSuccessor();
11 
12 protected: 
13     Handle();
14     Handle(Handle* succ);
15 
16 private: 
17     Handle* _succ; 
18 };
19 
20 class ConcreteHandleA:public Handle 
21 { 
22 public: 
23     ConcreteHandleA();
24     ~ConcreteHandleA();
25     ConcreteHandleA(Handle* succ);
26     void HandleRequest();
27 
28 protected:
29 private:
30 };
31 
32 class ConcreteHandleB:public Handle 
33 { 
34 public: 
35     ConcreteHandleB();
36     ~ConcreteHandleB();
37     ConcreteHandleB(Handle* succ);
38     void HandleRequest();
39 protected:
40 private:
41 };
42 
43 #endif
Handle.h
 1 #include "Handle.h"
 2 #include <iostream>
 3 using namespace std;
 4 
 5 Handle::Handle()
 6 { 
 7     _succ = 0;
 8 }
 9 Handle::~Handle() 
10 { 
11     delete _succ; 
12 }
13 Handle::Handle(Handle* succ) 
14 { 
15     this->_succ = succ; 
16 }
17 void Handle::SetSuccessor(Handle* succ) 
18 { 
19     _succ = succ;
20 }
21 Handle* Handle::GetSuccessor() 
22 {
23     return _succ;
24 }
25 void Handle::HandleRequest() 
26 {
27 
28 }
29 ConcreteHandleA::ConcreteHandleA() 
30 {
31 
32 }
33 ConcreteHandleA::ConcreteHandleA(Handle* succ):Handle(succ) 
34 {
35 
36 }
37 ConcreteHandleA::~ConcreteHandleA() 
38 {
39 
40 }
41 void ConcreteHandleA::HandleRequest() 
42 { 
43     if (this->GetSuccessor() != 0) 
44     { 
45         cout<<"ConcreteHandleA 我把处理权给后继节点....."<<endl; 
46         this->GetSuccessor()->HandleRequest(); 
47     } 
48     else 
49     { 
50         cout<<"ConcreteHandleA 没有后继了,我必须自己处理...."<<endl; 
51     } 
52 }
53 ConcreteHandleB::ConcreteHandleB() 
54 {
55 
56 }
57 ConcreteHandleB::ConcreteHandleB(Handle* succ):Handle(succ) 
58 {
59 
60 }
61 ConcreteHandleB::~ConcreteHandleB() 
62 {
63 
64 }
65 void ConcreteHandleB::HandleRequest() 
66 { 
67     if (this->GetSuccessor() != 0) 
68     { 
69         cout<<"ConcreteHandleB 我把处理权给后继节点....."<<endl; 
70         this->GetSuccessor()->HandleRequest(); 
71     } 
72     else 
73     { 
74         cout<<"ConcreteHandleB 没有后继了,我必须自己处理...."<<endl;
75     }
76 }
Handle.cpp
 1 #include "Handle.h"
 2 #include <iostream>
 3 using namespace std;
 4 
 5 int main(int argc,char* argv[]) 
 6 { 
 7     Handle* h1 = new ConcreteHandleA();
 8     Handle* h2 = new ConcreteHandleB();
 9     h1->SetSuccessor(h2);
10     h1->HandleRequest();
11     return 0; 
12 }
main.cpp

posted on 2015-07-24 11:32  那个人好像一条狗  阅读(183)  评论(0编辑  收藏  举报