其他分享
首页 > 其他分享> > 职责链模式(Chain Of Responsibility)

职责链模式(Chain Of Responsibility)

作者:互联网

设计模式系列

Chain Of Responsibility职责链模式——对象行为模式

1.意图

使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。

 

2.适用性

 

3.结构

 

4.参与者

—— 定义一个处理请求的接口

—— (可选)实现后继链

—— 处理它所负责的请求

—— 可访问它的后继者

—— 如果可处理该请求,就处理之;否则将该请求转发给它的后继者

—— 向链上的具体处理者(ConcreteHandler)对象提交请求

 

5.效果

Responsibility链有下列有点和缺点(liabilities);

1)降低耦合度

2)增强了给对象指派职责的灵活性

3)不保证被接受

 

6.案例

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

template <class T>
string MyConvertToString(T value)
{
    stringstream ss;
    ss << value;
    return ss.str();
}

//顶层的抽象类,规范了击鼓传花的组合能力
class Handle
{
public:
    void setSuccessor(Handle* pSuccessor)
    {
        this->m_pHandle = pSuccessor;
    }
    virtual string handleFeeRequest(double fee) = 0;
protected:
    Handle* m_pHandle;
};

class PrjManager :public Handle
{
public:
    string handleFeeRequest(double fee)
    {
        string strTemp = "";
        if (fee < 500)
        {
            strTemp = "项目经理同意" + MyConvertToString(fee) + "费用";
            return strTemp;
        }
        else
        {
            if (this->m_pHandle != nullptr)
            {
                return m_pHandle->handleFeeRequest(fee);
            }
        }
        return strTemp;
    }
};

class DepManager :public Handle
{
public:
    string handleFeeRequest(double fee)
    {
        string strTemp = "";
        if (fee >= 500 && fee < 1000)
        {
            strTemp = "部门经理同意" + MyConvertToString(fee) + "费用";
            return strTemp;
        }
        else
        {
            if (this->m_pHandle != nullptr)
            {
                return m_pHandle->handleFeeRequest(fee);
            }
        }
        return strTemp;
    }
};

class CEOManager :public Handle
{
public:
    string handleFeeRequest(double fee)
    {
        string strTemp = "";
        if (fee >= 1000)
        {
            strTemp = "CEO经理同意" + MyConvertToString(fee) + "费用";
            return strTemp;
        }
        else
        {
            if (this->m_pHandle != nullptr)
            {
                return m_pHandle->handleFeeRequest(fee);
            }
        }
        return strTemp;
    }
};
int main(void) {
    //先要组装我们的责任链
    Handle* pH1 = new PrjManager;
    Handle* pH2 = new DepManager;
    Handle* pH3 = new CEOManager;
    pH1->setSuccessor(pH2);
    pH2->setSuccessor(pH3);
    cout << pH1->handleFeeRequest(128) << endl;
    cout << pH1->handleFeeRequest(512) << endl;
    cout << pH1->handleFeeRequest(1024) << endl;
    system("pause");
    return 0;
}

 

 

设计模式系列 https://blog.csdn.net/nie2314550441/article/details/105849726

 

标签:handleFeeRequest,fee,return,职责,Chain,strTemp,pHandle,Responsibility,string
来源: https://blog.csdn.net/nie2314550441/article/details/105907524