职责链模式(Chain of Responsibility):使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
职责链模式好处在于可以简化对象之间的相互连接,它们只需保持一个指向其后继者的引用,而不需保持它所有的接受者的引用。
比如:一个员工的所有请求都只需告诉经理,如经理不能解决则交由总监解决。而不需要员工向总监请求。
UML:
//抽象类
class Manager
{
public:
Manager(Manager *superior, string name) :m_superior(superior), m_name(name) {}
virtual void RequestApplication(string name, int num) = 0;
protected:
Manager *m_superior; //上级
string m_name;
};
//经理
class CommonManager:public Manager
{
public:
CommonManager(Manager *superior, string name) :Manager(superior, name) {}
void RequestApplication(string name, int num)
{
if (num <= 5)
{
cout << "CommonManager: " << m_name << "批准 " << name << num << " 天请假" << endl;
}
else
{
m_superior->RequestApplication(name, num); //自己不能处理则交由上级处理
}
}
};
//总监
class Majordomo :public Manager
{
public:
Majordomo(Manager *superior, string name) :Manager(superior, name) {}
void RequestApplication(string name, int num)
{
if (num <= 15)
{
cout << "Majordomo: " << m_name << "批准 " << name << num << " 天请假" << endl;
}
else
{
m_superior->RequestApplication(name, num);
}
}
};
//总经理
class GeneralManager :public Manager
{
public:
GeneralManager(Manager *superior, string name) :Manager(superior, name) {}
void RequestApplication(string name, int num)
{
if (num <= 30)
{
cout << "GeneralManager: " << m_name << "批准 " << name << num << " 天请假" << endl;
}
else
{
cout << "GeneralManager: " << m_name << "你还是辞职吧" << endl;
}
}
};
int main()
{
Manager *zonjinli = new GeneralManager(NULL, "ZonJinLi");
Manager *zonjian = new Majordomo(zonjinli, "ZonJian");
Manager *jinli = new CommonManager(zonjian, "JinLi");
//请求都由经理处理,但是实际处理由具体管理类来处理,客户端不需要知道
jinli->RequestApplication("yu", 5);
jinli->RequestApplication("yu", 15);
jinli->RequestApplication("yu", 30);
jinli->RequestApplication("yu", 40);
system("pause");
return 0;
}