责任链模式
1. 概念讲解
- 责任链模式(Chain of Responsibility Pattern)为请求创建了一个处理对象的链(就好比于工厂的流水线作业一样,工人干完一个程序交由下一个工人进行操作,下一个工人干完后又交由下下一个工人进行操作)。
- 发起请求和具体处理请求的过程解耦:职责链上的处理者负责处理请求,客户只需要将请求发送到职责链上即可,无需关心请求的处理细节和请求的传递。
2. 如何实现责任链模式?
- 处理器抽象类:定义了处理请求的接口或者抽象类,提供了处理请求的的方法和设置下一个处理者的方法。
- 具体的处理器实现类:实现或者继承抽象这角色,具体逻辑根据实际确定。
- 保存处理器信息:以集合或者链表(netty源码实现)形式保存所有处理器实例信息。
- 处理执行:发起请求调用,通过责任链处理请求。
上述是实现责任链模式的4 个基本要素,下图是基于集合和链表方式实现责任链模式伪代码。
3. 参照netty实现一个责任链模式
首先定义一个抽象类,通过实现该抽象类的子类去执行链上节点doHandler()方法;
abstract class AbstractHandler {
/** * 处理器,这个处理器就做一件事情,在传入的字符串中增加一个尾巴.. */
abstract void doHandler(HandlerChainContext handlerChainContext, Object arg0); // handler方法
}
定义一个context,主要负责维护链和链的doHandler()方法的执行;
class HandlerChainContext {
HandlerChainContext next; // 下一个节点
AbstractHandler handler;
public HandlerChainContext(AbstractHandler handler) {
this.handler = handler;
}
void handler(Object arg0) {
this.handler.doHandler(this, arg0);
}
/** * 继续执行下一个 */
void runNext(Object arg0) {
if (this.next != null) {
this.next.handler(arg0);
}
}
}
定义AbstractHandler的实现类
class Handler1 extends AbstractHandler {
@Override
void doHandler(HandlerChainContext handlerChainContext, Object arg0) {
arg0 = arg0.toString() + "..handler1的小尾巴.....";
System.out.println("我是Handler1的实例,我在处理:" + arg0);
// 继续执行下一个
handlerChainContext.runNext(arg0);
}
}
class Handler2 extends AbstractHandler {
@Override
void doHandler(HandlerChainContext handlerChainContext, Object arg0) {
arg0 = arg0.toString() + "..handler2的小尾巴.....";
System.out.println("我是Handler2的实例,我在处理:" + arg0);
// 继续执行下一个
handlerChainContext.runNext(arg0);
}
}
以上Handler类都是继承了AbstractHandler,实现了doHandler()方法。每个方法执行不同的逻辑后将数据向下传递,传递到下一个链路节点。
定义测试主类
public class PipelineDemo {
/** * 初始化链的时候造一个head,作为责任链的开始,但是并没有具体的处理 */
public HandlerChainContext head = new HandlerChainContext(new AbstractHandler() {
@Override
void doHandler(HandlerChainContext handlerChainContext, Object arg0) {
handlerChainContext.runNext(arg0);
}
});
public void requestProcess(Object arg0) {
this.head.handler(arg0);
}
public void addLast(AbstractHandler handler) {
HandlerChainContext context = head;
while (context.next != null) {
context = context.next;
}
context.next = new HandlerChainContext(handler);
}
public static void main(String[] args) {
PipelineDemo pipelineChainDemo = new PipelineDemo();
pipelineChainDemo.addLast(new Handler2());
pipelineChainDemo.addLast(new Handler1());
pipelineChainDemo.addLast(new Handler1());
pipelineChainDemo.addLast(new Handler2());
// 发起请求
pipelineChainDemo.requestProcess("火车呜呜呜~~");
}
}
4. 参考文章
- https://juejin.cn/post/6844903512506122253
- https://blog.csdn.net/wangkang19890121/article/details/106086141/
- https://cloud.tencent.com/developer/article/1796236
- https://blog.csdn.net/weixin_39267363/article/details/99706242
正文到此结束