实现拦截器主要是在actionInvocation里面,interceptor在构造方法装载,然后在invoke方法里面循环加载,每个interceptor里面invoke下一个interceptor,直到action,然后倒着输出每个interceptor中invoke后面的方法。
package com.ceair.core.util;
public interface Interceptor {
public void interceptor(ActionInvocation invocation);
}
package com.ceair.core.util;
public class FirstInterceptor implements Interceptor {
public void interceptor(ActionInvocation invocation) {
System.out.println("1");
invocation.invoke();
System.out.println("-1");
}
}
package com.ceair.core.util;
public class SecondInterceptor implements Interceptor {
public void interceptor(ActionInvocation invocation) {
System.out.println("2");
invocation.invoke();
System.out.println("-2");
}
}
package com.ceair.core.util;
public class Action {
public void execute() {
System.out.println("Action");
}
}
package com.ceair.core.util;
import java.util.ArrayList;
import java.util.List;
public class ActionInvocation {
List<Interceptor> list = new ArrayList<Interceptor>();
int index = -1;
Action a = new Action();
public ActionInvocation() {
this.list.add(new FirstInterceptor());
this.list.add(new SecondInterceptor());
}
public void invoke() {
index ++;
if (index >= this.list.size()) {
a.execute();
} else {
this.list.get(index).interceptor(this);
}
}
}
package com.ceair.core.util;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new ActionInvocation().invoke();
}
}