设计模式1:责任链模式

1.HandlerExecutionChain

// 1. 执行主体为HandlerExecutionChain。
public class HandlerExecutionChain {

    // 2.主体属性handler。为拦截处理的对象
    private final Object handler;
    
    // 3.主体属性interceptorList。为拦截处理逻辑对象。xx为处理参数
    //   3.1 HandlerInterceptor.boolean preHandle(xx,Object handler)。前置处理
    //   3.2 HandlerInterceptor.void postHandle((xx,Object handler)。后置处理
    //   3.3 HandlerInterceptor.void afterCompletion((xx,xx1)。最终处理
	private final List<HandlerInterceptor> interceptorList = new ArrayList<>();
    
    // 4.主体属性interceptorIndex。标识处理进度
	private int interceptorIndex = -1;

    // 构造对象
    public HandlerExecutionChain(Object handler, List<HandlerInterceptor> interceptorList)
    
    // 前置处理逻辑。前置处理逻辑失败则触发最终处理
    //    a.interceptor1.preHandle为true,interceptor2.preHandle为true,则返回true
    //    b.interceptor1.preHandle为true,interceptor2.preHandle为false,则
    //      interceptor1.afterCompletion()
    boolean applyPreHandle(xx) throws Exception {
		for (int i = 0; i < this.interceptorList.size(); i++) {
			HandlerInterceptor interceptor = this.interceptorList.get(i);
			if (!interceptor.preHandle(request, response, this.handler)) {
				triggerAfterCompletion(request, response, null);
				return false;
			}
			this.interceptorIndex = i;
		}
		return true;
	}
    
    // 后置处理逻辑
    void applyPostHandle(xx,hanlder)
			throws Exception {

		for (int i = this.interceptorList.size() - 1; i >= 0; i--) {
			HandlerInterceptor interceptor = this.interceptorList.get(i);
			interceptor.postHandle(this.handler);
		}
	}  
    
    // 最终处理逻辑
    void triggerAfterCompletion(xx,xx1) {
		for (int i = this.interceptorIndex; i >= 0; i--) {
			HandlerInterceptor interceptor = this.interceptorList.get(i);
			try {
				interceptor.afterCompletion(xx, xx1);
			}
			catch (Throwable ex2) {
				logger.error("HandlerInterceptor.afterCompletion threw exception", ex2);
			}
		}
	} 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值