设计模式-职责链

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

#include <QCoreApplication>
#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[])
{
    QCoreApplication a(argc, argv);
    Handler1 h1;
    Handler2 h2;
    Handler3 h3;
    h1.setNextChain(&h2);
    h2.setNextChain(&h3);

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值