标签:
1.拦截器接口
public interface Interceptor { void interceptor(ActionInvocation invocation); }
2.给接口做3个实现
public class FirstInterceptor implements Interceptor { public void interceptor(ActionInvocation invocation) { System.out.println(1); invocation.invoke(); System.out.println(-1); } } public class SecondInterceptor implements Interceptor{ public void interceptor(ActionInvocation invocation) { System.out.println(2); invocation.invoke(); System.out.println(-2); } } public class ThirdInterceptor implements Interceptor{ public void interceptor(ActionInvocation invocation) { System.out.println(3); invocation.invoke(); System.out.println(-3); } }
3.一个Action对象
public class Action { public void execute(){ System.out.println("execute执行了!!!"); } }
4.ActionInvocation在初始化的时候,把3个拦截器的实现初始化到List里,模拟拦截器栈
1 public class ActionInvocation { 2 List<Interceptor> interceptors = new ArrayList<Interceptor>(); 3 int index = -1; 4 Action a = new Action(); 5 6 public ActionInvocation(){ 7 this.interceptors.add(new FirstInterceptor()); 8 this.interceptors.add(new SecondInterceptor()); 9 this.interceptors.add(new ThirdInterceptor()); 10 } 11 public void invoke() { 12 index++; 13 14 if (index >= this.interceptors.size()) { 15 a.execute(); 16 } else { 17 this.interceptors.get(index).interceptor(this); 18 } 19 } 20 }
5.运行
public class Main { public static void main(String[] args) { new ActionInvocation().invoke(); } }
6.结果
1
2
3
execute执行了!!!
-3
-2
-1
标签:
原文地址:http://www.cnblogs.com/yanghyun/p/4472447.html