/**
* 模拟webwork的拦截器
*/
import java.util.ArrayList;
import java.util.Iterator;
public class ActionInvocation {
public boolean executed = false;
//这个intercepters必须是成员变量
protected Iterator intercepters;
public String resultCode;
public String invoke() throws Exception {
if (executed) {
throw new IllegalStateException("Action has already executed");
}
if (intercepters.hasNext()) {
// 因为intercepters是类成员变量,所以递归执行到这里的时候,会执行一个Intercepter的intercept方法,知道都迭代完毕
Intercepter intercepter = (Intercepter) intercepters.next();
//递归
// here is recure point ,programm run to here
// then save the state into the stack ,and jump to the top of the method run again
// and so and so util the condition to else branch
resultCode = intercepter.intercept(this);
} else {
resultCode = invokeActionOnly();
}
if (!executed) {
System.out.println("now it is time to run the action, and this method should not run again!!");
executed = true;
}
return resultCode;
}
private String invokeActionOnly() {
System.out.println("run invokeActionOnly() ");
// invoke和intercept的递归的时候返回都将是这个值,所以这个返回值能够保存到最后,
// 只是在两个方法之间被多次地传递
return "here is action return value,it's the result;";
}
public ActionInvocation(){
ArrayList ay=new ArrayList();
ay.add(new Intercepter(1));
ay.add(new Intercepter(2));
ay.add(new Intercepter(3));
intercepters=ay.iterator();
}
public static void main(String[] args) {
ActionInvocation actionInvocation =new ActionInvocation();
try {
System.out.println(actionInvocation.invoke());
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class Intercepter {
private int id;
public Intercepter(int id){
this.id=id;
}
public String intercept(ActionInvocation actionInvocation) throws Exception {
String result = null;
System.out.println("run the intercept()"+this.id);
String resultCode=actionInvocation.invoke();
System.out.println("after the action run,run the intercept continue "+this.id);
return resultCode;
}
}