1、Command 介面。它是 Commons Chain 中最重要的介面,代表 Chain 中某一步要執行的命令,只有一個方法 boolean execute(Context context)。回傳 true 表示 Chain 處理結束、其他命令不再被呼叫;回傳 false 則 Chain 會繼續呼叫下一個 Command,直到:命令回傳 true、命令拋出例外,或抵達 Chain 末尾。
2、Context 介面。它代表命令執行的上下文,用於在命令間共享資訊的傳遞。Context 的父介面是 Map,ContextBase 實現了它;在 Web 環境下可使用 WebContext 類及其子類(FacesWebContext、PortletWebContext、ServletWebContext)。
3、Chain 介面。它代表「命令鏈」,要執行的命令需先加入 Chain。Chain 的父介面是 Command,ChainBase 實現了它。
4、Filter 介面。其父介面是 Command,是一種特殊的 Command。除了 execute,它還包含 boolean postprocess(Context context, Exception exception)。無論 Chain 以何種方式結束,Commons Chain 都會在執行 Filter 的 execute 之後執行 postprocess。execute 的執行順序與 Filter 在 Chain 中的位置一致,postprocess 的順序則相反:若依序定義 filter1、filter2,execute 順序為 filter1 -> filter2,postprocess 順序為 filter2 -> filter1。
5、Catalog 介面。它是邏輯命名的 Chain 與 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;
}
}
2. 註冊命令並建立要執行的 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);
}
}