首先来看一段代码
#define Context int //这个是函数的参数
class IHandler {
public:
virtual ~IHandler() {}
void SetNextHandler(IHandler *next) {
next = next;
}
bool Handle(ctx) {
if (CanHandle(ctx)) {
return HandleRequest();
} else if (GetNextHandler()) {
return GetNextHandler()->HandleRequest(ctx);
} else {
// err
}
}
protected:
virtual bool HandleRequest(const Context &ctx) = 0;
virtual bool CanHandle(const Context &ctx) =0;
IHandler * GetNextHandler() {
return next;
}
private:
IHandler *next;
};
上图便是最经典的责任链模式 他的子类可以通过继承他 然后形成一种链式的处理结构 如果我能处理 那便处理 如果我不能处理 那么我交给下一个来处理
只需要简单的改动就能成为功能链模式 什么叫功能链模式呢 就是 我处理完了再交给下一个处理 既
下图这种代码
#define rusult int //函数返回结果
#define Context int //这个是函数的参数
class IHandler {
public:
virtual ~IHandler() {}
void SetNextHandler(IHandler *next) {
next = next;
}
bool Handle(ctx) {
if (CanHandle(ctx)) {
result ret=HandleRequest();
if(next!=nullptr)
return next->HandleRequest();
else return ret;
}
}
protected:
virtual bool HandleRequest(const Context &ctx) = 0;
virtual bool CanHandle(const Context &ctx) =0;
IHandler * GetNextHandler() {
return next;
}
private:
IHandler *next;
};
然后每一个想要加入这种链式结构的子类只需要像下图这样定义即可
class HandleByMainProgram : public IHandler {
protected:
virtual bool HandleRequest(const Context &ctx){
//
}
virtual bool CanHandle() {
//
}
};
class HandleByProjMgr : public IHandler {
protected:
virtual bool HandleRequest(const Context &ctx){
//
}
virtual bool CanHandle() {
//
}
};
class HandleByBoss : public IHandler {
public:
virtual bool HandleRequest(const Context &ctx){
//
}
protected:
virtual bool CanHandle() {
//
}
};
int main () {
IHandler * h1 = new MainProgram();
IHandler * h2 = new HandleByProjMgr();
IHandler * h3 = new HandleByBoss();
h1->SetNextHandler(h2);
h2->SetNextHandler(h3);
Context ctx;
h1->handle(ctx);
return 0;
}
如上图所示 在调用h1的handle函数过后 便会链式的调用所有handle函数