责任链,我感受对就根据需求动态的组织一些工做流程,好比完成一件事有5个步骤,而第1步,第2步,第3步它们的顺序能够在某些时候是不固定的,而这就符合责任链的范畴,咱们根据需求去设计咱们的这些链条,去本身指定它们的执行顺序,下面看个人一个例子。ide
抽像责任测试
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); } } }
具体责任this
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); } } }
具体链条code
/** * 第一个责任链条. */ 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")); }
结果递归
创建 编辑 删除 读取