介绍责任链模式(Chain of Responsibility Pattern)
为请求创建了一个接收者对象的链。这种模式给予请求的类型,对请求的发送者和接收者进行解耦。例如:现在我们要开一个化学制品公司,我们要到环境保护局去申请,但是各种各样的局,我们要选择哪个呢,让责任链来帮助我们。当然我们还可以实现logger日志。
参与者
- Handler(Bureau):定义一个处理请求的接口,实现后继链。
- ConcreteHandler(Handler子类):处理它负责的请求,并可以访问它的后继者。
- Client(main函数):发送请求。
代码实现
const int TIB_id = 1;
const int EPB_id = 2;
const int CIB_id = 3;
class Request{//用户请求
public:
Request():index(0),bureau_id(0),req(""){}
int getIndex()
{
return index;
}
void setIndex(int a)
{
index = a;
}
int getBureauId()
{
return bureau_id;
}
void setBureauId(int a)
{
bureau_id = a;
}
void setReq(std::string req_)
{
req = std::move(req_);
}
std::string & getReq()
{
return req;
}
private:
int index;
std::string req;
int bureau_id;
};
class Bureau{ //局子Handler
public:
Bureau():id(0),nextBureau(nullptr){}
explicit Bureau(int id_):id(id_),nextBureau(nullptr){}
public:
int id;
virtual void Sign(Request request) = 0;
Bureau *nextBureau;
void Search2Sign(Request request)//实现后继链
{
if(this->id == request.getBureauId())
{
Sign(request);
return;
}
if(nextBureau!= nullptr){
nextBureau->Sign(request);
}
}
};
class TIB : public Bureau{ //工商局ConcreteHandler
public:
TIB():Bureau(1){}
void Sign(Request request) override
{
std::cout<<"工商局(ID:"<<request.getBureauId()<<")处理请求(ID:"<<id<<")事件:"<<request.getReq()<<std::endl;
}
};
class EPB : public Bureau{ //环境保护局ConcreteHandler
public:
EPB():Bureau(2){}
void Sign(Request request) override
{
std::cout<<"环境保护局(ID:"<<request.getBureauId()<<")处理请求(ID:"<<id<<")事件:"<<request.getReq()<<std::endl;
}
};
class CIB:public Bureau{ //商检局ConcreteHandler
public:
CIB():Bureau(3){}
void Sign(Request request) override
{
std::cout<<"商检局(ID:"<<request.getBureauId()<<")处理请求(ID:"<<id<<")事件:"<<request.getReq()<<std::endl;
}
};
int main()
{
auto *begin = new CIB();
auto *epb = new EPB();
auto *end = new TIB();
begin->nextBureau = epb;
epb->nextBureau = end;
Request r;
r.setIndex(2);
r.setBureauId(TIB_id); //请求2让TIB处理
r.setReq("开公司");
begin->Search2Sign(r);
return 0;
}
输出
环境保护局(ID:1)处理请求(ID:2)事件:开公司
特点
- 降低耦合度
- 增强了给对象指派职责的灵活性
- 不保证请求一定被处理
参考
- 《设计模式:可复用面向对象的软件基础》
网友评论