摘要:/** * 第一個責任鏈條. */ public class WorkFlow1 extends WorkFlow { @Override protected ChainHandler getChainHandler() { ChainHandler chainHandler = new CreateService()。/** * 責任鏈流程處理者. */ public abstract class WorkFlow { private ChainHandler command。

責任鏈,我感覺對就根據需求動態的組織一些工作流程,比如完成一件事有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"));
    }

結果

建立
編輯
刪除
讀取
相關文章