职责链模式:使多个对象都用机会处理请求,从而避免请求的发送者和接受者之间的耦合关系。将这些对象链接成一条链,并沿着这条链传递该请求,直到有一个对象处理他为之。其思想很简单,考虑员工要求加薪。公司的管理者一共有三级,总经理、总监、经理,若是一个员工要求加薪,应该想主管的经理申请,若是加薪的数量在经理的职权内,那么经理能够直接批准,不然将申请上交给总监。总监的处理方式也同样,总经理能够处理全部的请求。这个就是典型的职责链模式,请求的处理造成了一条链,知直到有对象处理请求。给出这个例子的UML图:ios
#include <string> #include <iostream> using namespace std; //抽象管理者 class Manager { protected: Manager *m_manager; string m_name; public: Manager(Manager *manager, string name):m_manager(manager), m_name(name){} virtual void DealWithRequest(string employeeName, int num){} }; //经理 class CommonManager:public Manager { public: CommonManager(Manager * manager, string name):Manager(manager, name){} void DealWithRequest(string employeeName, int num) { if(num < 500)//在经理的职权范围内 { cout << "经理" << m_name <<"批准"<<employeeName<<"加薪"<<num<<"元"<<endl<<endl; } else { cout << "经理"<<m_name << "无权处理,交由总监处理"<<endl; m_manager->DealWithRequest(employeeName,num); } } }; //总监 class Majordomo: public Manager { public: Majordomo(Manager *manager, string name):Manager(manager,name) {} void DealWithRequest(string name, int num) { if(num < 1000) //总监职权以内 { cout<<"总监"<<m_name<<"批准"<<name<<"加薪"<<num<<"元"<<endl<<endl; } else { cout<<"总监"<<m_name<<"没法处理,交由总经理处理"<<endl; m_manager->DealWithRequest(name, num); } } }; //总经理 class GeneralManager: public Manager { public: GeneralManager(Manager *manager, string name):Manager(manager,name) {} void DealWithRequest(string name, int num) //总经理能够处理全部请求 { cout<<"总经理"<<m_name<<"批准"<<name<<"加薪"<<num<<"元"<<endl<<endl; } }; int main() { Manager *general = new GeneralManager(NULL, "A"); //设置上级,总经理没有上级 Manager *majordomo = new Majordomo(general, "B"); //设置上级 Manager *common = new CommonManager(majordomo, "C"); //设置上级 common->DealWithRequest("D",300); //员工D要求加薪 common->DealWithRequest("E", 600); common->DealWithRequest("F", 1000); delete common; delete majordomo; delete general; return 0; }
结果图:dom
经理C批准D加薪300元 经理C无权处理,交由总监处理! 总监B批准E加薪600元 经理C无权处理,交由总监处理! 总监B没法处理,交由总经理处理 总经理A批准F加薪1000元
参考地址:http://blog.csdn.net/wuzhekai1985/article/details/6673892spa