設計模式——職責鏈模式(C++實現)
阿新 • • 發佈:2017-05-24
delet hand jin void ng- nbsp request req oot
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(intrequest) = 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(intrequest) 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天,時間太長,超過公司規定
設計模式——職責鏈模式(C++實現)