背景
在繁琐的业务流程处理中,通常采用面向过程的设计方法将流程拆分成N个步骤,每个步骤执行独立的逻辑。
public void process(params){
doFirst(params);
doSecond(params);
....
doLast(params);
}
但是这样剥离仍然是不彻底的,修改其中一个步骤仍然可能影响其他步骤(同一个类修改,不符合开闭原则)。在这种场景下,有一种经典的设计模式-责任链模式,可以将这些子步骤封装成独立的handler,然后通过pipeline将其串联起来。
常见的责任链模式会设计如下:
总体来看,纯手动编写有以下问题:
-
正确性:实现复杂度较高,短时间手工编写容易出错
-
开发效率:涉及多个类的实现,需要花费不少时间进行测试非业务的pipeline流程,ROI不高
-
复用性:不同业务流程难以复用同一套pipeline的关键代码
那有没有一套靠谱的框架能够解决上述问题呢?有的,它就是foldright/auto-pipeline,是责任链领域的"lombok"!
Quirk Start
下面以 读取系统配置 为例,读取逻辑如下:
-
从本地配置文件读取,读取成功则直接返回,否则执行下一步
-
从系统变量读取,返回对应的值
为了实现这个需求,读取配置接口定义如下:
public interface ConfigSource {
String get(String key);
}
如果使用auto-pipeline,该如何
以下大部分内容引至auto-pipeline官网: https://github.com/foldright/auto-pipeline
- 引入Maven依赖
<dependency>
<groupId>com.foldright.auto-pipeline</groupId>
<artifactId>auto-pipeline-processor</artifactId>
<version>0.2.0</version>
<scope>provided</scope>
</dependency>
- 在需要生成pipeline的接口上加上@AutoPipeline
只需为这个接口加上@AutoPipeline
@AutoPipeline
public interface ConfigSource {
String get(String key);
}
- 实现pipeline的handler
public class MapConfigSourceHandler implements ConfigSourceHandler {
private final Map<String, String> map;
public MapConfigSourceHandler(Map<String, String> map) {
this.map = map;
}
@Override
public String get(String key, ConfigSourceHandlerContext context) {
String value = map.get(key);
if (StringUtils.isNotBlank(value)) {
return value;
}
return context.get(key);
}
}
public class SystemConfigSourceHandler implements ConfigSourceHandler {
public static final SystemConfigSourceHandler INSTANCE = new SystemConfigSourceHandler();
@Override
public String get(String key, ConfigSourceHandlerContext context) {
String value = System.getProperty(key);
if (StringUtils.isNotBlank(value)) {
return value;
}
return context.get(key);
}
}
- 使用pipeline
Map<String, String> mapConfig = new HashMap<String, String>();
mapConfig.put("hello", "world");
ConfigSourceHandler mapConfigSourceHandler = new MapConfigSourceHandler(mapConfig);
ConfigSource pipeline = new ConfigSourcePipeline()
.addLast(mapConfigSourceHandler)
.addLast(SystemConfigSourceHandler.INSTANCE);
pipeline.get("hello");
// get value "world"
// from mapConfig / mapConfigSourceHandler
pipeline.get("java.specification.version")
// get value "1.8"
// from system properties / SystemConfigSourceHandler
实现原理
业务接口通过生成的Pipeline构造实现,Pipeline负责责任链的组装及调用链表的首个节点(head)。首个节点如果处理完成有返回值,则直接返回;否则传递给下一个节点。如果处理到最后一个节点(tail)返回仍然为空,则直接返回空。
以获取配置为例:
-
用户实现:
-
ConfigSource
-
用户自定义的 获取配置的接口
-
Handler实现:
-
MapConfigSourceHandler 、SystemConfigSourceHandler
-
AutoPipeline生成
-
ConfigSourcePipeline
-
含义:责任链管道
-
核心作用:将ConfigSourceHandler 串联成链表
-
ConfigSourceHandlerContext
-
含义:Handler的上下文,相比传统责任链,新增了获取全局Pipeline的能力
-
AbstractConfigSourceHandlerContext
-
含义:Handler的上下文的抽象类
-
数据结构:主要由三个部分组成:pre、next、handler
-
核心作用:通过handler().get(key , findNextCtx()) 实现了 String get(String key) 方法
-
DefaultConfigSourceHandlerCo