责任链,我感觉对就根据需求动态的组织一些工作流程,比如完成一件事有5个步骤,而第1步,第2步,第3步它们的顺序可以在某些时候是不固定的,而这就符合责任链的范畴,我们根据需求去设计我们的这些链条,去自己指定它们的执行顺序,下面看我的一个例子。
出现的对象
- 抽象责任
- 具体责任
- 抽象链条
- 具体链条
对象的解释
- 抽象责任,也可以说是一个行为,它规定的这类行为的签名
- 具体责任,去实现抽象责任,它就是我们上面说的每个步骤的实现
- 抽象链条,它将会去初始化你的责任链条,提供外部调用链条的入口,但没有具体指定链条的顺序
- 具体链条,只负责指定这些链条的顺序
代码实现
抽像责任
public abstract class ChainHandler {
private ChainHandler next;
public abstract void execute(HandlerParameters parameters);
public ChainHandler getNext() {
return next;
}
public ChainHandler setNext(ChainHandler next) {
this.next = next;
return this.next;
}
/**
* 链条的处理方法,单向链表的遍历。
*
* @param handlerParameters
*/
public void ProcessRequest(ChainHandler command, HandlerParameters handlerParameters) {
if (command == null) {
throw new IllegalArgumentException("请先使用setCommand方法去注册命令");
}
command.execute(handlerParameters);
// 递归处理下一级链条
if (command.getNext() != null) {
ProcessRequest(command.getNext(), handlerParameters);
}
}
}
具体责任
public class CreateService extends ChainHandler {
@Override
public void execute(HandlerParameters parameters) {
System.out.println("建立");
}
}
public class EditService extends ChainHandler {
@Override
public void execute(HandlerParameters parameters) {
System.out.println("编辑");
}
}
public class RemoveService extends ChainHandler {
@Override
public void execute(HandlerParameters parameters) {
System.out.println("删除");
}
}
抽象链条
/**
* 责任链流程处理者.
*/
public abstract class WorkFlow {
private ChainHandler command;
public WorkFlow() {
this.command = getChainHandler();
}
protected abstract ChainHandler getChainHandler();
/**
* 链条的处理方法,单向链表的遍历。
*
* @param handlerParameters
*/
public void ProcessRequest(HandlerParameters handlerParameters) {
if (command == null) {
throw new IllegalArgumentException("请先使用setCommand方法去注册命令");
}
command.execute(handlerParameters);
// 递归处理下一级链条
if (command.getNext() != null) {
command = command.getNext();
ProcessRequest(handlerParameters);
}
}
}
具体链条
/**
* 第一个责任链条.
*/
public class WorkFlow1 extends WorkFlow {
@Override
protected ChainHandler getChainHandler() {
ChainHandler chainHandler = new CreateService();
chainHandler.setNext(new EditService())
.setNext(new RemoveService())
.setNext(new ReadService());
return chainHandler;
}
}
测试
@Test
public void chainFlow1() {
WorkFlow workFlow = new WorkFlow1();
workFlow.ProcessRequest(new HandlerParameters("doing", "test"));
}
结果
建立
编辑
删除
读取