标签:定义 image virtual and ons ret ptr color 接收
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