【1】什么是责任链模式? 责任链模式: 【2】责任链模式的代码示例: 代码示例:
#include<iostream> #include<string> using namespace std; class Request { public: string requestType; string requestContent; int number; }; class Manager { protected: string name; Manager *superior; public: Manager(string name) { this->name = name; } void setSuperior(Manager *superior) { this->superior = superior; } virtual void requestApplications(Request *request) = 0; }; class CommonManager : public Manager { public: CommonManager(string name) : Manager(name) {} void requestApplications(Request *request) { if (request->requestType == "请假" && request->number <= 2) { cout << name << " " << request->requestContent << " 请假天数: " << request->number << " 被批准" << endl; } else { if (superior != NULL) { superior->requestApplications(request); } } } }; class Majordomo : public Manager { public: Majordomo(string name) : Manager(name) {} void requestApplications(Request *request) { if (request->requestType == "请假" && request->number <= 5) { cout << name << " " << request->requestContent << " 请假天数: " << request->number << " 被批准" << endl; } else { if (superior != NULL) { superior->requestApplications(request); } } } }; class GeneralManager : public Manager { public: GeneralManager(string name) : Manager(name) {} void requestApplications(Request *request) { if (request->requestType == "请假") { cout << name << " " << request->requestContent << " 请假天数: " << request->number << " 被批准" << endl; } } }; int main() { CommonManager *jingli = new CommonManager("经理"); Majordomo *zongjian = new Majordomo("总监"); GeneralManager *zongjingli = new GeneralManager("总经理"); jingli->setSuperior(zongjian); zongjian->setSuperior(zongjingli); Request *request = new Request(); request->requestType = "请假"; request->requestContent = "李俊宏请假"; request->number = 1; jingli->requestApplications(request); request->requestType = "请假"; request->requestContent = "李俊宏请假"; request->number = 4; jingli->requestApplications(request); request->requestType = "请假"; request->requestContent = "李俊宏请假"; request->number = 10; jingli->requestApplications(request); return 0; } //Result: /* 经理 李俊宏请假 请假天数: 1 被批准 总监 李俊宏请假 请假天数: 4 被批准 总经理 李俊宏请假 请假天数: 10 被批准 */
http://www.cnblogs.com/Braveliu/p/3956793.html