職責鏈模式:使多個對象都用機會處理請求,從而避免請求的發送者和接受者之間的耦合關係。將這些對象鏈接成一條鏈,並沿着這條鏈傳遞該請求,直到有一個對象處理他爲之。其思想很簡單,考慮員工要求加薪。公司的管理者一共有三級,總經理、總監、經理,若是一個員工要求加薪,應該想主管的經理申請,若是加薪的數量在經理的職權內,那麼經理能夠直接批准,不然將申請上交給總監。總監的處理方式也同樣,總經理能夠處理全部的請求。這個就是典型的職責鏈模式,請求的處理造成了一條鏈,知直到有對象處理請求。給出這個例子的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