首页 > 代码库 > 责任链模式

责任链模式

责任链(Chain of Responsibility)模式

意图:避免请求发送者与接收者耦合在一起,让多个对象都有可能接收请求,将这些对象连接成一条链,并且沿着这条链传递请求,直到有对象处理它为止。

主要解决:职责链上的处理者负责处理请求,客户只需要将请求发送到职责链上即可,无须关心请求的处理细节和请求的传递,所以职责链将请求的发送者和请求的处理者解耦了。

 

代码:

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

// 请求类型
enum class RequestType
{
    REQ_HANDLE1,
    REQ_HANDLE2,
    REQ_HANDLE3
};

class Request
{
public:
    Request(string des, RequestType type) :_description(des), _reqType(type){}
    inline const string& getDescription() const { return _description; }
    inline RequestType getType() const { return _reqType; }
    void setType(const RequestType  type){ _reqType = type; }
private:
    string _description;   // 描述信息
    RequestType _reqType;  // 类型
};

class ChainHandler
{
private:
    void sendRequestToNextChain(const Request &req)
    {
        if (_nextChain != nullptr)
        {
            _nextChain->handle(req);
        }
    }

protected:
    virtual bool canHandleRequest(const Request &req) = 0;  // 判断能否处理请求
    virtual void processRequest(const Request &req) = 0;  // 处理请求

public:
    ChainHandler()
    {
        _nextChain = nullptr;
    }
   virtual ~ChainHandler() {}
void setNextChain(ChainHandler *next) { _nextChain = next; } void handle(const Request &req) // 接收请求 { if (canHandleRequest(req)) processRequest(req); else sendRequestToNextChain(req); } private: ChainHandler *_nextChain; }; class Handler1 : public ChainHandler { protected: virtual bool canHandleRequest(const Request &req) { return req.getType() == RequestType::REQ_HANDLE1; } virtual void processRequest(const Request &req) // 处理请求 { cout << "Handler1 process request: " << req.getDescription() << endl; } }; class Handler2 : public ChainHandler { protected: virtual bool canHandleRequest(const Request &req) { return req.getType() == RequestType::REQ_HANDLE2; } virtual void processRequest(const Request &req) { cout << "Handler2 process request: " << req.getDescription() << endl; } }; class Handler3 : public ChainHandler { protected: virtual bool canHandleRequest(const Request &req) { return req.getType() == RequestType::REQ_HANDLE3; } virtual void processRequest(const Request &req) { cout << "Handler3 process request: " << req.getDescription() << endl; } }; void test() { Handler1 h1; Handler2 h2; Handler3 h3; h1.setNextChain(&h2); h2.setNextChain(&h3); Request req("produce car...", RequestType::REQ_HANDLE1); h1.handle(req); req.setType(RequestType::REQ_HANDLE2); h1.handle(req); req.setType(RequestType::REQ_HANDLE3); h1.handle(req); } int main() { test(); cin.get(); return 0; }

效果:

技术分享

 

责任链模式