歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Commons Chain使用

Commons Chain使用

日期:2017/3/1 10:04:39   编辑:Linux編程

基本對象

1、Command接口。它是Commons Chain中最重要的接口,表示在Chain中的具體某一步要執行的命令。它只有一個方法:boolean execute(Context context)。如果返回true,那麼表示Chain的處理結束,Chain中的其他命令不會被調用;返回false,則Chain會繼續調用下一個Command,直到:

- Command返回true;

- Command拋出異常;

- Chain的末尾;

2、Context接口。它表示命令執行的上下文,在命令間實現共享信息的傳遞。Context接口的父接口是Map,ContextBase實現了Context。對於web環境,可以使用WebContext類及其子類(FacesWebContext、PortletWebContext和ServletWebContext)。

3、Chain接口。它表示“命令鏈”,要在其中執行的命令,需要先添加到Chain中。Chain的父接口是Command,ChainBase實現了它。

4、Filter接口。它的父接口是Command,它是一種特殊的Command。除了Command的execute,它還包括一個方法:boolean postprocess(Context context, Exception exception)。Commons Chain會在執行了Filter的execute方法之後,執行postprocess(不論Chain以何種方式結束)。Filter的執行execute的順序與Filter出現在Chain中出現的位置一致,但是執行postprocess順序與之相反。如:如果連續定義了filter1和filter2,那麼execute的執行順序是:filter1 -> filter2;而postprocess的執行順序是:filter2 -> filter1。

5、Catalog接口。它是邏輯命名的Chain和Command集合。通過使用它,Command的調用者不需要了解具體實現Command的類名,只需要通過名字就可以獲取所需要的Command實例。


基本使用

1. 執行由順序的命令組成的流程,假設這條流程包含1、2和3步。

public class Command1 implements Command {

public boolean execute(Context arg0) throws Exception {

System.out.println("Command1 is done!");

return false;

}

}

public class Command2 implements Command {

public boolean execute(Context arg0) throws Exception {

System.out.println("Command2 is done!");

return false;

}

}

public class Command3 implements Command {

public boolean execute(Context arg0) throws Exception {

System.out.println("Command3 is done!");

return true;

}

}


注冊命令,創建執行的Chain:

public class CommandChain extends ChainBase {

//增加命令的順序也決定了執行命令的順序

public CommandChain(){

addCommand( new Command1());

addCommand( new Command2());

addCommand( new Command3());

}

public static void main(String[] args) throws Exception{

Command process = new CommandChain();

Context ctx= new ContextBase();

process.execute( ctx);

}

}

Copyright © Linux教程網 All Rights Reserved