Linux C++ 047-设计模式之责任链模式
本节关键字:Linux、C++、设计模式、责任链模式
相关库函数:
简介
责任链模式是面向对象中的一种软件设计模式,它包含了一些命令对象和一些处理对象,每个处理对象决定它能处理那些命令对象,它也知道应该把自己不能处理的命令对象交下一个处理对象,该模式还描述了往该链添加新的处理对象的方法。
代码示例
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 == "qingjia" && request->number <= 2) {cout << name << " " << "pizhun" << request->requestContent << "number: " << 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 == "qingjia" && request->number <= 5) {cout << name << " " << "pizhun" << request->requestContent << "number: " << 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 == "qingjia") {cout << name << " " << "pizhun" << request->requestContent << "number: " << request->number << endl;}}
};
int main_Request()
{CommonManager* jingli = new CommonManager("jingli");Majordomo* zongjian = new Majordomo("zongjian");GeneralManager* zongjingli = new GeneralManager("zongjingli");jingli->setSuperior(zongjian);zongjian->setSuperior(zongjingli);Request* request = new Request();request->requestType = "qingjia";request->requestContent = "LI qingjia";request->number = 1;jingli->requestApplications(request);request->requestType = "qingjia";request->requestContent = "LI qingjia";request->number = 4;jingli->requestApplications(request);request->requestType = "qingjia";request->requestContent = "LI qingjia";request->number = 10;jingli->requestApplications(request);return 0;
}
/* 运行结果:
jingli pizhun LI qingjia number: 1
zongjian pizhun LI qingjia number: 4
zongjingli pizhun LI qingjia number: 10
*/
// 对于抽象基类的派生类:经理类,总监类,总经理类都能够处理请求,只不过根据请求的内容不同,他们自己如果不能处理,需要请求自己的上级处理,那么在这里面需要定义设置自己的上级以及处理请求的成员函数
// 客户端:实例化请求对象,以及经理对象,并初始化请求对象的内容以及经理之间的上下级关系,请求直接交给最底层的经理来处理即可(它内部直到这个请求最终谁有权力处理)
//