职责链模式

职责链模式

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

enum ReqestType{
  HANDLE1,
  HANDLE2,
  HANDLE3
};

class Reqest
{
public:
  Reqest(const std::string& desc,ReqestType request_type):
  	desc_(desc),
  	request_type_(request_type)
  {
      
  }
	ReqestType getReqestType() const
  {
    return request_type_;
  }
  const std::string& getDesc() const
  {
    return desc_;
  }
  
private:
  std::string desc_;
  ReqestType request_type_;
}

class ChainHandler
{
public:
  ChainHandler():
  	next_chain_hander_(nullptr)
  {
    
	}
  void setNextChain(ChainHandler* next_chain_hander)
  {
    next_chain_hander_=next_chain_hander
  }
  void handle(const Reqest& reqest)
  {
    if(canHandleRequest(reqest))
      processRequest(reqest)
    else
      sendReqestToNextHandler(reqest)
  }
  
protected:
  virtual bool canHandleRequest(const Reqest& reqest) = 0;
  virtual void processRequest(const Reqest& reqest) = 0;
  
private:
  void sendReqestToNextHandler(const Reqest& reqest)
  {
    if(next_chain_hander_)
      next_chain_hander->handle(reqest);
  }
  
  ChainHandler* next_chain_hander_;
};

class Handler1 : public ChainHandler
{
  virtual bool canHandleRequest(const Reqest& reqest) override
  {
    return reqest.getReqestType()==ReqestType::HANDLE1;
  }
  virtual void processRequest(const Reqest& reqest) override
  {
    std::cout<<"Handler1:"<<reqest.getDesc()<<std::endl;
  }
}

class Handler2 : public ChainHandler
{
  virtual bool canHandleRequest(const Reqest& reqest) override
  {
    return reqest.getReqestType()==ReqestType::HANDLE2;
  }
  virtual void processRequest(const Reqest& reqest) override
  {
    std::cout<<"Handler2:"<<reqest.getDesc()<<std::endl;
  }
}

class Handler3 : public ChainHandler
{
  virtual bool canHandleRequest(const Reqest& reqest) override
  {
    return reqest.getReqestType()==ReqestType::HANDLE3;
  }
  virtual void processRequest(const Reqest& reqest) override
  {
    std::cout<<"Handler3:"<<reqest.getDesc()<<std::endl;
  }
}

int main()
{
  Handler1 h1;
  Handler2 h2;
  Handler3 h3;
  h1.setNextChain(&h2);
  h2.setNextChain(&h3);
  
  Reqest reqest("task",ReqestType::HANDLE3);
  h1.handle(reqest);
  return 0;
}

UML类图

职责链模式

上一篇:android webview X509Util: Failed to validate the certificate chain, error: java.security.cert.Cert


下一篇:rip明文密文认证实验