public class Main {
public static void main(String[] args) {
new ActionInvocation().invoke();
}
}
public interface Interceptor { //定义接口
public void intercept(ActionInvocation invocation) ;
}
import java.util.ArrayList;
import java.util.List;
public class ActionInvocation {
List<Interceptor> interceptors = new ArrayList<Interceptor>(); // 定义一系列接口集合
int index = -1;
Action a = new Action();
public ActionInvocation() {
this.interceptors.add(new FirstInterceptor()); // 向集合中添加
this.interceptors.add(new SecondInterceptor());
}
public void invoke() {
index++;
if (index >= this.interceptors.size()) { // 循环完成
a.execute();
} else {
this.interceptors.get(index).intercept(this); //用index上的interceptors调用intercept
}
}
}
public class FirstInterceptor implements Interceptor { // 实现Interceptor接口
public void intercept(ActionInvocation invocation) {
System.out.println(1);
invocation.invoke();
System.out.println(-1);
}
}
public class SecondInterceptor implements Interceptor {// 实现Interceptor接口
public void intercept(ActionInvocation invocation) {
System.out.println(2);
invocation.invoke();
System.out.println(-2);
}
}
public class Action {
public void execute() {
System.out.println("execute!");
}
}