A way of passing a request between a chain of objects to find the object that can handle the request. 定义了请求的传递方向,通过多个对象对请求的传递,实现一个复杂的逻辑操作,将负责的需求颗粒化逐一实现每一个对象分内的需求,并将请求顺序地传递,直到一个对象处理它为止。
动机:给多个对象处理一个请求的机会,从而解耦发送者和接收者。
适用性:有多个对象可以处理一个请求,但是需要在运行的时刻来具体确定;或者在不明确指定接收者的情况下向多个对象提交一个请求;亦或是处理一个请求的对象集合应该被动态指定。
效果:
- 降低耦合度,使得一个对象不需要关心其它哪一个具体的对象来处理请求。对象只需要知道该请求会被「正确」处理;接收者和发送方都没有对方的明确消息,且链中的对象不需要知道链的结构。
- 增强了给对象指派职责的灵活性。可以在责任链上动态增加处理节点。
- 但不能够保证被「接受」。有可能会存在到链末端都未处理的情形。
结构实现:
经典的 Case 可以使用 Tomcat 中 Container 责任链来说明。整个容器体系,包括(Engine, Host, Context, Wrapper Servlet)就是通过一个责任链连接在一起的。这个链一直将请求正确地传递给最终处理请求的那个 Servlet。
interface HelperHandler {helpHandler(): void;}// concrete handlerclass PrintButton implements HelpHander {constructor(dialog: PrintDialog) {this.parent = dialog;};helpHandler() {if (this.ownHelpInformation()) {this.showHelp();} else {this.parent.helpHandler();}}onClick(event: Event) {this.helpHandler(event.target);}}// concrete handlerclass PrintDialog {constructor(application: PrintApplication) {this.parent = application;this.printButton = new PrintButton(this);};helpHandler() {if (this.haveAvailiableInformation()) {this.showHelp();return;}this.parent.helpHandler();}}// concrete handlerclass PrintApplication {constructor(config: appConfig) {this.printDialog = new PrintDialog(this);};helpHandler() {this.showHelp();}}
该设计模式经常与 Composite 模式「双拼」,即「父节点」就是它职责链的上一级传递。
