责任链模式
动机
在软件构建过程中,一个请求可能被多个对象处理,但是每个请求在运行时只能有一个接受者,如果显式指定,将必不可少地带来请求发送者与接受者的紧耦合。
如何使请求的发送者不需要指定具体的接受者?让请求的接受者自己在运行时决定来处理请求,从而使两者解耦。
解决方法
使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递请求,直到有一个对象处理它为止。
例子
#include <iostream>
#include <string>
using namespace std;
enum class RequestType
{
REQ_HANDLER1,
REQ_HANDLER2,
REQ_HANDLER3
};
class Reqest
{
string description;
RequestType reqType;
public:
Reqest(const string & desc, RequestType type): description(desc), reqType(type) {}
RequestType getReqType() const { return reqType; }
const string& getDescription() const { return description; }
};
class ChainHandler
{
ChainHandler *nextChain;
void sendReqestToNextHandler(const Reqest & req)
{
if (nextChain != nullptr)
{
nextChain->handle(req);
}
}
protected:
virtual bool canHandleRequest(const Reqest & req) = 0; // 能否处理请求
virtual void processRequest(const Reqest & req) = 0; // 处理请求
public:
ChainHandler() { nextChain = nullptr; }
void setNextChain(ChainHandler *next) { nextChain = next; }
void handle(const Reqest & req)
{
if (canHandleRequest(req))
{
processRequest(req);
}
else
{
sendReqestToNextHandler(req);
}
}
};
class Handler1: public ChainHandler
{
protected:
bool canHandleRequest(const Reqest &req) override
{
return req.getReqType() == RequestType::REQ_HANDLER1;
}
void processRequest(const Reqest &req) override
{
cout << "Handler1 is handle reqest: " << req.getDescription() << endl;
}
};
class Handler2: public ChainHandler
{
protected:
bool canHandleRequest(const Reqest &req) override
{
return req.getReqType() == RequestType::REQ_HANDLER2;
}
void processRequest(const Reqest &req) override
{
cout << "Handler2 is handle reqest: " << req.getDescription() << endl;
}
};
class Handler3: public ChainHandler
{
protected:
bool canHandleRequest(const Reqest &req) override
{
return req.getReqType() == RequestType::REQ_HANDLER3;
}
void processRequest(const Reqest &req) override
{
cout << "Handler3 is handle reqest: " << req.getDescription() << endl;
}
};
int main()
{
Handler1 h1;
Handler2 h2;
Handler3 h3;
h1.setNextChain(&h2);
h2.setNextChain(&h3);
Reqest req("process task ... ", RequestType::REQ_HANDLER3);
h1.handle(req);
return 0;
}
优缺点
优点:降低耦合度。它将请求的发送者和接收者解耦。简化了对象。使得对象不需要知道链的结构。增强给对象指派职责的灵活性。通过改变链内的成员或者调动它们的次序,允许动态地新增或者删除责任。增加新的请求处理类很方便。
缺点:不能保证请求一定被接收。系统性能将受到一定影响,而且在进行代码调试时不太方便,可能会造成循环调用。可能不容易观察运行时的特征,有碍于除错。