1. 意图
使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。
将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
2. 两种角色
抽象处理者(Handler)、具体处理者(Concrete Handler)
3. 优点
3.1 降低耦合度。简化了对象的相互连接,仅需保持一个指向后继者的引用。
3.2 增强了给对象指派职责的灵活性。可以在运行时刻动态地增加或改变职责。
4. 缺点
4.1 不保证请求一定被处理(没有相应的处理者或使用不当)
5. 相关模式
5.1 职责链常与组合一起使用。
6. 代码示意(C++)
#pragma once
#include <iostream>
#include <string>
using namespace std;
class Request
{
int m_type;
string m_content;
public:
Request(int type, const string& content) :m_type(type), m_content(content) {
}
int GetType() { return m_type; }
string GetContent() { return m_content; }
};
class Handler
{
Handler* m_pNextHandler;
public:
Handler(Handler* pNextHandler) {
m_pNextHandler = pNextHandler;
}
virtual void HandleRequest(Request* pRequest) {
if (0 != m_pNextHandler) {
m_pNextHandler->HandleRequest(pRequest);
}
else {
cout << "Not handled, request id:" << pRequest->GetType() << endl;
}
}
};
class ConcreteHandler1 :public Handler
{
public:
ConcreteHandler1(Handler* pNextHandler) :Handler(pNextHandler) {
}
virtual void HandleRequest(Request* pRequest) {
if (1 == pRequest->GetType()) {
cout << "ConcreteHandler1 handled:" << pRequest->GetContent() << endl;
}
else {
Handler::HandleRequest(pRequest);
}
}
};
class ConcreteHandler2 :public Handler
{
public:
ConcreteHandler2(Handler* pNextHandler) :Handler(pNextHandler) {
}
virtual void HandleRequest(Request* pRequest) {
if (2 == pRequest->GetType()) {
cout << "ConcreteHandler2 handled:" << pRequest->GetContent() << endl;
}
else {
Handler::HandleRequest(pRequest);
}
}
};
#include "Handler.h"
int main() {
Handler* pHandler2 = new ConcreteHandler2(0);
Handler* pHandler1 = new ConcreteHandler1(pHandler2);
Request request1(1,"hello");
Request request2(2, "hi");
pHandler1->HandleRequest(&request1);
pHandler1->HandleRequest(&request2);
pHandler2->HandleRequest(&request1);
delete pHandler1;
delete pHandler2;
return 0;
}
运行结果:
6.1 每个具体处理者只需关注自己能处理的请求,其它请求丢给后继者(3.1)
6.2 pHandler2只能处理一个请求,因为它在职责链的末端(4.1)