码迷,mamicode.com
首页 > 编程语言 > 详细

c++ 行为型模式-责任链(Chain of Responsibility)

时间:2020-01-25 22:12:08      阅读:81      评论:0      收藏:0      [点我收藏+]

标签:定义   image   virtual   and   ons   ret   ptr   color   接收   

1) 意图

使多个对象连成一条链,沿着这条链传递请求,直到有个对象处理它为止。

2) 结构

 技术图片

 

 其中:

  1. Handler定义一个处理请求的接口
  2. ConcreteHandler处理它所负责的请求
  3. Client向链上具体处理提交请求

 

3) 适用性

  1. 有多个对象可以处理一个请求,哪个对象处理该请求运行时刻自动确定
  2. 想在不明确指定接收者的情况下向多个对象中的一个提交一个请求
  3. 可处理一个请求的对象集合应被动态指定

4) 举例

 1 #include <iostream>
 2 #include <list>
 3 class  Handler
 4 {
 5 public:
 6     Handler(Handler* successor):m_successor(successor){}
 7     virtual ~Handler() 
 8     {
 9         if (m_successor)
10         {
11             delete m_successor;
12             m_successor = NULL;
13         }
14     }
15     virtual void  HandleRequest(int num) = 0;
16 protected:
17     Handler* m_successor;
18 };
19 class  ConcreateHandler1 : public Handler
20 {
21 public:
22     ConcreateHandler1(Handler* successor) :Handler(successor) {}
23     virtual ~ConcreateHandler1() {}
24     virtual void  HandleRequest(int num)
25     {
26         if (num == 1)
27         {
28             std::cout << "ConcreateHandler1 HandleRequest" << std::endl;
29         }
30         else if (m_successor != NULL)
31         {
32             m_successor->HandleRequest(num);
33         }
34         else
35         {
36             std::cout << "error ConcreateHandler1 m_successor null" << std::endl;
37 
38         }
39     }
40 };
41 class  ConcreateHandler2 : public Handler
42 {
43 public:
44     ConcreateHandler2(Handler* successor) :Handler(successor) {}
45     virtual ~ConcreateHandler2() {}
46     virtual void  HandleRequest(int num)
47     {
48         if (num == 2)
49         {
50             std::cout << "ConcreateHandler2 HandleRequest" << std::endl;
51         }
52         else if (m_successor != NULL)
53         {
54             m_successor->HandleRequest(num);
55         }
56         else
57         {
58             std::cout << "error ConcreateHandler1 m_successor null" << std::endl;
59 
60         }
61     }
62 };
63 
64  int main()
65  {
66      Handler* ptr1 = new ConcreateHandler1(NULL);
67      Handler* ptr2 = new ConcreateHandler2(ptr1);
68      ptr2->HandleRequest(1);
69      ptr2->HandleRequest(2);
70      ptr2->HandleRequest(0);
71 
72      delete ptr2;
73      system("pause");
74  }

 

c++ 行为型模式-责任链(Chain of Responsibility)

标签:定义   image   virtual   and   ons   ret   ptr   color   接收   

原文地址:https://www.cnblogs.com/ho966/p/12233442.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!