设计模式-职责链

shienh 2020年01月29日 275次浏览

职责链(Chain of Responsibility)模式的定义:为了避免请求发送者与多个请求处理者耦合在一起,将所有请求的处理者通过前一对象记住其下一个对象的引用而连成一条链;当有请求发生时,可将请求沿着这条链传递,直到有对象处理它为止。

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

enum class RequestType{
    REQ_HANDLER1,
    REQ_HANDLER2,
    REQ_HANDLER3
};

class Request{
public:
    Request(const string& dest,RequestType req):description(dest),reqType(req){}
    RequestType getType()const {return reqType;}
    const string getdescription(){return description;}
private:
    string description;
    RequestType reqType;
};


class ChainHandler{
public:
    ChainHandler(){next=NULL;}
    void sendRequestToNext(Request& req){
        if(NULL!=next){
            next->handle(req);
        }
    }

    void setNextChain(ChainHandler* next){this->next=next;}

    void handle(Request& req){
        if(canHanleRequest(req)){
            processRequest(req);
        }
        else{
            sendRequestToNext(req);
        }
    }

protected:
    virtual bool canHanleRequest(const Request& req)=0;
    virtual void processRequest(Request& req)=0;

private:
    ChainHandler* next;
};


class Handler1:public ChainHandler{
public:

protected:
    bool canHanleRequest(const Request &req){
        return req.getType() == RequestType::REQ_HANDLER1;
    }

    void processRequest(Request& req){
        cout<<"headler1 is handle request:"<<req.getdescription();
    }
};

class Handler2:public ChainHandler{
public:

protected:
    bool canHanleRequest(const Request &req){
        return req.getType() == RequestType::REQ_HANDLER2;
    }

    void processRequest(Request& req){
        cout<<"headler2 is handle request:"<<req.getdescription();
    }
};

class Handler3:public ChainHandler{
public:

protected:
    bool canHanleRequest(const Request &req){
        return req.getType() == RequestType::REQ_HANDLER3;
    }

    void processRequest(Request& req){
        cout<<"headler3 is handle request:"<<req.getdescription();
    }
};

int main(int argc, char *argv[])
{
    Handler1 h1;
    Handler2 h2;
    Handler3 h3;
    h1.setNextChain(&h2);
    h2.setNextChain(&h3);

    Request req("process task",RequestType::REQ_HANDLER2);
    h2.handle(req);
    return 0;
}