这里写自定义目录标题
职责链模式 (Chain ofResponsibility)
使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
优点
- 当客户提交一个请求时,请求是沿链传递直至有一个对象负责处理它,这样的好处是请求者不用管哪个对象来处理,反正该请求会被处理。这就使得接收者和发送者都没有对方的明确信息,且链中的对象自己也并不知道链的结构。结果是职责链可简化对象的相互连接,它们仅需保持一个指向其后继者的引用,而不需保持它所有的候选接受者的引用,大大降低了耦合度。
- 由于是在客户端来定义链的结构,可以随时地增加或修改处理一个请求的结构。增强了给对象指派职责的灵活性.
结构图
example
在公司申请加薪,需要一层层的上报审批。
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
class Request
{
string name;
string type;
string content;
int num;
public:
Request(string n, string t, string c, int nu) : name(n), type(t), content(c), num(nu) {}
string getType()
{
return type;
}
string getContent()
{
return content;
}
int getNum()
{
return num;
}
};
// 抽象管理者
class Manager
{
protected:
string name;
Manager *next;
public:
Manager(string n) : name(n) {}
void setNext(Manager *n)
{
next = n;
}
virtual void handleQuest(Request *r) = 0;
};
// 经理
class CommonManager : public Manager
{
public:
CommonManager(string s) : Manager(s) {}
virtual void handleQuest(Request *r)
{
if (r->getType() == "请假" && r->getNum() < 2)
{
cout << name << "批准" << endl;
}
else
{
cout << name << " 无权处理" << endl;
next->handleQuest(r);
}
}
};
// 总监
class Major : public Manager
{
public:
Major(string s) : Manager(s) {}
virtual void handleQuest(Request *r)
{
if (r->getType() == "请假" && r->getNum() < 5)
{
cout << name << "批准" << endl;
}
else
{
cout << name << " 无权处理" << endl;
next->handleQuest(r);
}
}
};
// 总经理
class GeneralManager : public Manager
{
public:
GeneralManager(string s) : Manager(s) {}
virtual void handleQuest(Request *r)
{
if (r->getType() == "请假")
{
cout << "批准" << endl;
}
else if (r->getNum() < 500)
{
cout << "批准" << endl;
}
else
{
cout << name << ": 继续努力,才能加薪" << endl;
}
}
};
int main()
{
Request *q = new Request("mini", "加薪", "工作一年了,业绩突出,请求加薪", 500);
Manager *m1 = new CommonManager("jingli");
Manager *m2 = new Major("zongjian");
Manager *m3 = new GeneralManager("zongjingli");
m1->setNext(m2);
m2->setNext(m3);
m1->handleQuest(q);
return 0;
}