/**
* 模擬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是類成員變量,所以遞歸執(zhí)行到這里的時候,會執(zhí)行一個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;
}
}