1 2 3 | public interface Interceptor { void intercept(Execution execution, InterceptorChain chain) throws Exception; } |
1 2 3 | public interface InterceptorChain { void doInterceptor(Execution execution) throws Exception; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class InterceptorChainImpl implements InterceptorChain { private final Interceptor[] interceptors; private int index = 0; private Object result = null; InterceptorChainImpl(Interceptor[] interceptors) { this.interceptors = interceptors; } Object getResult() { return result; } public void doInterceptor(Execution execution) throws Exception { if(index==interceptors.length) result = execution.execute(); else { // must update index first, otherwise will cause stack overflow: index++; interceptors[index-1].intercept(execution, this); } } } |
1 2 3 4 5 6 7 8 9 10 | class Dispatcher { ... private Interceptor[] interceptors; void handleExecution(Execution execution, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { InterceptorChainImpl chains = new InterceptorChainImpl(interceptors); chains.doInterceptor(execution); handleResult(request, response, chains.getResult()); } } |
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) | Powered by Discuz! 7.0.0 |