1 #include <iostream> 2 #include <string> 3 4 using namespace std; 5 6 7 class Handler 8 { 9 public: 10 Handler(Handler* pstHandler): m_pstHandler(pstHandler) 11 { 12 13 } 14 15 virtual void HandleRequest(int request) = 0; 16 17 protected: 18 Handler* m_pstHandler; 19 }; 20 21 class ConcreteHandler1: public Handler 22 { 23 public: 24 ConcreteHandler1(Handler* pstHandler): Handler(pstHandler) 25 { 26 27 } 28 29 virtual void HandleRequest(int request) 30 { 31 if (request < 7) 32 { 33 cout<< "组长:批假"<< request<< "天"<< endl; 34 } 35 else 36 { 37 m_pstHandler->HandleRequest(request); 38 } 39 } 40 }; 41 42 class ConcreteHandler2: public Handler 43 { 44 public: 45 ConcreteHandler2(Handler* pstHandler): Handler(pstHandler) 46 { 47 48 } 49 50 virtual void HandleRequest(int request) 51 { 52 if (request < 15) 53 { 54 cout<< "总监:批假"<< request<< "天"<< endl; 55 } 56 else 57 { 58 m_pstHandler->HandleRequest(request); 59 } 60 } 61 }; 62 63 class ConcreteHandler3: public Handler 64 { 65 public: 66 ConcreteHandler3(Handler* pstHandler): Handler(pstHandler) 67 { 68 69 } 70 71 virtual void HandleRequest(int request) 72 { 73 if (request < 30) 74 { 75 cout<< "经理:批假"<< request<< "天"<< endl; 76 } 77 else 78 { 79 cout<< "经理:"<< request<< "天,时间太长,超过公司规定"<< endl; 80 } 81 } 82 }; 83 84 int main(int argc, char* argv[]) 85 { 86 Handler* jingli = new ConcreteHandler3(NULL); 87 Handler* zongjian = new ConcreteHandler2(jingli); 88 Handler* zuzhang = new ConcreteHandler1(zongjian); 89 90 zuzhang->HandleRequest(12); 91 zuzhang->HandleRequest(15); 92 zuzhang->HandleRequest(5); 93 zuzhang->HandleRequest(31); 94 95 delete jingli; 96 delete zongjian; 97 delete zuzhang; 98 99 return 0; 100 } 101 ////////////////////////////////// 102 [root@ ~/learn_code/design_pattern/20_chain]$ ./chain 103 总监:批假12天 104 经理:批假15天 105 组长:批假5天 106 经理:31天,时间太长,超过公司规定
原文:http://www.cnblogs.com/070412-zwc/p/6896732.html