Commons Chain使用
Commons Chain使用
基本对象
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);
}
}
|
评论暂时关闭