职责链模式(Chain of Responsibility):使多个对象都有机会处理请求,从而避免请求的发送者和接受之间的耦合关系。将这个对象连城一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
职责链模式处理中,当客户有一个请求时,请求沿着链传递直到有一个对象处理它,我们在设计的时候也必须保证每一个请求都能被处理。接受者和发送者都没有对方的明确信息,而且链中的每个对象自己也不知道自己处于在链的哪个位置。我们只需要把链设置好,也就是对每个链的节点设置后后或者前节点来承接请求(当当前链节点不能处理请求时)。而且我们可以随时增加或者修改该处理链的结构,增加了设计的灵活性。
下文的例子需要我们事先给每个具体的管理者设置他的上司是哪个类,也就是设置后继者。我们需要在每个具体管理类处理请求时,做出判断是否可以处理当前请求,如不能把请求递交给后继者处理。
#ifndef RESPONSIBILITY_H #define RESPONSIBILITY_H #include <iostream> #include<string> using namespace std; class Request { friend class Manager; friend class CommonManager; friend class Majordomo; friend class GeneralManager; string requesttype; int number; public: Request(string st, int n) :requesttype(st), number(n){} }; class Manager { protected: string name; Manager * superior; public: Manager(){} Manager(string st) :name(st){} void Setsuperior(Manager * s) { superior = s; } virtual void RequestAppliancations(Request request)=0; }; class CommonManager :public Manager { public: CommonManager(string n) { name = n; } void RequestAppliancations(Request request) { if (request.requesttype == "请假"&&request.number <= 5) { cout << name << ": " << request.requesttype << ", 数量:" << request.number << " 被批准。\n"; } else if (superior != nullptr) superior->RequestAppliancations(request); } }; class Majordomo :public Manager { public: Majordomo(string n){ name = n; } void RequestAppliancations(Request request) { if (request.requesttype == "请假"&&request.number <= 10) { cout << name << ": " << request.requesttype << ", 数量:" << request.number << " 被批准。\n"; } else if (superior != nullptr) superior->RequestAppliancations(request); } }; class GeneralManager :public Manager { public: GeneralManager(string s) { name = s; } void RequestAppliancations(Request request) { if (request.requesttype == "请假") { cout << name << ": " << request.requesttype << ", 数量:" << request.number << " 被批准。\n"; } else { if (request.requesttype == "加薪"&&request.number<=500) cout << name << ": " << request.requesttype << ", 数量:" << request.number << " 被批准。\n"; else if(request.requesttype == "加薪" && request.number > 500) cout << name << ": " << request.requesttype << ", 数量:" << request.number << " 再说吧。\n"; } } }; #endif
#include "Responsibility.h" int main() { CommonManager xie("谢伟"); Majordomo zhao("赵浩"); GeneralManager hu("胡智"); xie.Setsuperior(&zhao); zhao.Setsuperior(&hu); Request rq1("请假", 4); Request rq2("请假", 10); Request rq3("加薪",400); Request rq4("加薪",1000); xie.RequestAppliancations(rq1); xie.RequestAppliancations(rq2); xie.RequestAppliancations(rq3); xie.RequestAppliancations(rq4); return 0; }
原文地址:http://blog.csdn.net/shiwazone/article/details/45817845