本系列所有文章来自李建忠老师的设计模式笔记,系列如下: 设计模式(一)面向对象设计原则 23种设计模式(二)组件协作之模板方法 23种设计模式(三)组件协作之策略模式 23种设计模式(四)组件协作之观察者模式 23种设计模式(五)单一职责之装饰模式 23种设计模式(六)单一职责之桥模式 23种设计模式(七)对象创建之工厂方法 23种设计模式(八)对象创建之抽象工厂 23种设计模式(九)对象创建之原型模式 23种设计模式(十)对象创建之构建器 23种设计模式(十一)对象性能之单件模式 23种设计模式(十二)对象性能之享元模式 23种设计模式(十三)接口隔离之门面模式 23种设计模式(十四)接口隔离之代理模式 23种设计模式(十五)接口隔离之适配器 23种设计模式(十六)接口隔离之中介者 23种设计模式(十七)状态变化之状态模式 23种设计模式(十八)状态变化之备忘录 23种设计模式(十九)数据结构之组合模式 23种设计模式(二十)数据结构之迭代器 23种设计模式(二十一)数据结构之职责链 23种设计模式(二十二)行为变化之命令模式 23种设计模式(二十三)行为变化之访问器 23种设计模式(二十四)领域规则之解析器
文章目录
动机模式定义代码要点总结
动机
在软件构建过程中, 一个请求可能被多个对象处理,但是每个请求在运行时只能有一个接受者,如果显式指定,将必不可少地带来请求发送者与接受者的紧耦合。
如何使请求的发送者不需要指定具体的接受者?让请求的接受者自己在运行时决定来处理请求,从而使两者解耦。
模式定义
使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递请求,直到有一个对象处理它为止。
代码
#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;
}
要点总结
Chain of Responsibility模式的应用场合在于“一个请求可能有,多个接受者,但是最后真正的接受者只有一个”, 这时候请求发送者与接受者的耦合有可能出现“变化脆弱”的症状,职责链的目的就是蒋三著解耦,从而更好地应对变化。
应用了Chain of Responsibility模式后,对象的职责分派将更具灵活性。我们可以在运行时动态添加/修改请求的处理职责。
如果请求传递到职责链的末尾仍得不到处理,应该有一个合理的缺省机制。这也是每个接受对象的责任,而不是发出请求的对象的责任。