責任鏈,我感受對就根據需求動態的組織一些工做流程,好比完成一件事有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")); }
結果遞歸
創建 編輯 刪除 讀取