首先看官方介绍:
A popular technique for organizing the execution of complex processing flows is the "Chain of Responsibility" pattern
很受欢迎的(流行的)对于复杂的流程处理方式,也就是通常说的,责任链设计模式了。
下面我们来个简单的使用:
1、首先加入依赖
<dependency>
<groupId>commons-chain</groupId>
<artifactId>commons-chain</artifactId>
<version>1.2</version>
</dependency>
To check for the most recent version of this library– go here.
2、首先我们就以我们最熟悉的业务场景,也是大多数demo 中使用到的
对于一个销售人员来说,要完成一个完整的销售过程,一般要遵循如下过程:
6.png这么一个过程 ,明显是一个流程处理的过程,怎么来代码实现呢?
或者如果实现了,又需要加入新的流程来了,怎么办呢?
怎么做到灵活实现兼容变更呢?
Apache common chain 就实现了这一责任链模式。
先来定义各个流程实现:
//获取客户信息
public class GetUserInfo implements Command {
public boolean execute(Context context) throws Exception {
System.out.println("Get user info begin");
context.put("userName", "Tom");
return false;
}
}
//预约试驾
public class TestDriver implements Command {
public boolean execute(Context context) throws Exception {
System.out.println("Test driver begin....");
return false;
}
}
//谈判
public class NegotiateSale implements Command {
public boolean execute(Context context) throws Exception {
System.out.println("This is Negotiate");
return false;
}
}
//支付
public class ArrangeFinancing implements Command {
public boolean execute(Context context) throws Exception {
System.out.println("This is arranging financing");
return false;
}
}
//交付
public class CloseSale implements Command {
public boolean execute(Context context) throws Exception {
System.out.println("Thanks," + context.get("userName") + ",enjoying your driving");
return false;
}
}
OK 这里,流程就全部定义好了,这里可以看到,我们都实现了一个Command接口,来定义我们具体的业务实现,并且有个 全局Context ,用来保存后续需要处理的参数传递。
好了,怎么串起来整个流程呢?
public class CommondChain extends ChainBase {
public CommondChain() {
super();
addCommand(new GetUserInfo());
addCommand(new TestDriver());
addCommand(new NegotiateSale());
addCommand(new ArrangeFinancing());
addCommand(new CloseSale());
}
public static void main(String[] args) {
CommondChain commondChain = new CommondChain();
Context context = new ContextBase();
try {
commondChain.execute(context);
} catch (Exception e) {
e.printStackTrace();
}
}
}
可以 run 起来了 哈哈哈,输入结果:
Get user info begin
Test driver begin....
This is Negotiate
This is arranging financing
Thanks,Tom,enjoying your driving
网友评论