设计模式——责任链模式

沿责任链传递请求,直到有一个对象处理为止。使多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系

设计模式——责任链模式_第1张图片

 

 

c++

 1 #include 
 2 #include <string>
 3 #include 
 4 using namespace std;
 5 
 6 class Request{
 7     public:
 8         string m_strContent;
 9         int m_nNumber;
10 };
11 class Manager{
12     protected:
13         Manager* manager;
14         string name;
15     public:
16         Manager(string temp){
17             name = temp;
18         }
19     void SetSuccessor(Manager* temp){
20         manager = temp;
21     } 
22     virtual void GetRequest(Request* request)=0;
23 };
24 class CommonManager:public Manager{
25     public:
26         CommonManager(string strTemp):Manager(strTemp){}
27         virtual void GetRequest(Request* request){
28             if(request->m_nNumber>=0 && request->m_nNumber<10){
29                 cout<"处理了"<m_nNumber<<"个请求"<<endl;
30             }else{
31                 manager->GetRequest(request);
32             }
33         }
34 };
35 class MajorDomo:public Manager{
36     public:
37         MajorDomo(string name):Manager(name){}
38         virtual void GetRequest(Request* request){
39             if(request->m_nNumber>=10){
40                 cout<"处理了"<m_nNumber<<"个请求"<<endl;
41             }
42         }
43 };
44 int main(){
45     Manager* common = new CommonManager("张经理");
46     Manager* major = new MajorDomo("李总监");
47     common->SetSuccessor(major);
48     Request* req = new Request();
49     
50     req->m_nNumber = 33;
51     common->GetRequest(req);
52     
53     req->m_nNumber=3;
54     common->GetRequest(req);
55     
56     return 0;
57 }

结果:

设计模式——责任链模式_第2张图片

你可能感兴趣的:(设计模式——责任链模式)