责任链模式
模式定义
- 责任链模式属于行为型模式,使多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系,将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理为止。
模式角色
- Handler 抽象类:处理请求对象的抽象类
- ConcreteHandler:处理请求的具体对象
UML 图
代码实例
#include <iostream>
using namespace std;
class Leader
{
public:
void setNext(Leader* nextLeader){
m_pstNextLeader = nextLeader;
}
Leader* getNext(){
return m_pstNextLeader;
}
virtual ~Leader(){}
virtual void handleRequest(int leaveDays) = 0;
private:
Leader* m_pstNextLeader;
};
class ClassAdviser : public Leader
{
public:
void handleRequest(int leaveDays){
if(leaveDays <= 2) {
cout << "ClassAdviser have permitted your holiday: " << leaveDays << endl;
}
else{
if(getNext() != nullptr){
getNext()->handleRequest(leaveDays);
}
else{
cout << "Holiday is too big, and nobody can perimit" << endl;
}
}
}
private:
};
class DepartmentHead : public Leader
{
public:
void handleRequest(int leaveDays){
if(leaveDays <= 7){
cout << "DepartmentHead have permitted your holiady: " << leaveDays << endl;
}
else{
if(getNext() != nullptr){
getNext()->handleRequest(leaveDays);
}
else{
cout << "Holiday is too big, and nobody can perimit" << endl;
}
}
}
private:
};
class Dean : public Leader
{
public:
void handleRequest(int leaveDays){
if(leaveDays <= 10){
cout << "Dean have permitted your holiady: " << leaveDays << endl;
}
else{
if(getNext() != nullptr){
getNext()->handleRequest(leaveDays);
}
else{
cout << "Holiday is too big, and nobody can perimit" << endl;
}
}
}
private:
};
int main()
{
Leader* pstClassAdviser = new ClassAdviser();
Leader* pstDepartment = new DepartmentHead();
Leader* pstDean = new Dean();
pstClassAdviser->setNext(pstDepartment);
pstDepartment->setNext(pstDean);
int leaveDays[5] = {1, 5, 7, 10, 13};
for(int i = 0; i < (int)(sizeof(leaveDays)/sizeof(leaveDays[0])); ++i){
pstClassAdviser->handleRequest(leaveDays[i]);
}
return 0;
}
优缺点
优点:
- 请求者与处理者的松耦合
- 处理类对象的添加和删除不影响处理逻辑
- 职责明确
缺点:
- 请求不一定被处理
- 责任链太长会影响系统性能
- 责任链的设定依赖客户端,可靠性会受到客户端影响