使得多个对象都有机会处理请求,避免请求的发送者和接收者之间的耦合关系。将对象连成一个链条,请求按照链条传递,直到可处理为止。
代码如下(示例):
//15.职责链条模式
enum REQUEST_TYPE
{
REQUEST_ASK_FOR_LEAVE=0,
REQUEST_ADD_SALARY
};
typedef struct _request
{
string text;
REQUEST_TYPE type;
int num; //天数或者薪水
}Request;
class Manager
{
public:
Manager(string istrName) :m_strName(istrName){};
void setSuperior(Manager *ipSuperior)
{
m_pSuperior = ipSuperior;
}
virtual void processRequest(Request iRequest) = 0;
protected:
Manager *m_pSuperior; //上级
string m_strName;
};
class CommonManager :public Manager
{
public:
CommonManager(string istrName) :Manager(istrName){};
void processRequest(Request iRequest) override
{
if (iRequest.type==REQUEST_ASK_FOR_LEAVE&&iRequest.num<=2)
{
cout << m_strName << "批准" << iRequest.text << iRequest.num << endl;
}
else
{
if (m_pSuperior)
{
m_pSuperior->processRequest(iRequest);
}
}
}
};
class Majordomo :public Manager
{
public:
Majordomo(string istrName) :Manager(istrName){};
void processRequest(Request iRequest) override
{
if (iRequest.type == REQUEST_ASK_FOR_LEAVE&&iRequest.num <= 5)
{
cout << m_strName << "批准" << iRequest.text << iRequest.num << endl;
}
else
{
if (m_pSuperior)
{
m_pSuperior->processRequest(iRequest);
}
}
}
};
class GeneralManager :public Manager
{
public:
GeneralManager(string istrName) :Manager(istrName){};
void processRequest(Request iRequest) override
{
if (iRequest.type == REQUEST_ASK_FOR_LEAVE)
{
cout << m_strName << "批准" << iRequest.text << iRequest.num << endl;
}
else if (iRequest.type == REQUEST_ADD_SALARY&&iRequest.num <= 500)
{
cout << m_strName << "批准" << iRequest.text << iRequest.num << endl;
}
else
{
cout << m_strName << "暂不批准" << iRequest.text << iRequest.num << endl;
}
}
};
int main()
{
Request request;
request.text = "小宋请假";
request.type = REQUEST_ASK_FOR_LEAVE;
request.num = 30;
CommonManager *pCommonManager = new CommonManager("www");
Majordomo *pMajordomo = new Majordomo("yyy");
GeneralManager *pGeneralManager = new GeneralManager("lll");
pCommonManager->setSuperior(pMajordomo);
pMajordomo->setSuperior(pGeneralManager);
pCommonManager->processRequest(request);
delete pCommonManager;
delete pMajordomo;
delete pGeneralManager;
system("pause");
}
<font color=#999AAA 暂无