责任链模式(Chain of Responsibility Pattern)

责任链模式

顾名思义,责任链模式(Chain of Responsibility Pattern)为请求创建了一个接收者对象的链。这种模式给予请求的类型,对请求的发送者和接收者进行解耦。这种类型的设计模式属于行为型模式。
在这种模式中,通常每个接收者都包含对另一个接收者的引用。如果一个对象不能处理该请求,那么它会把相同的请求传给下一个接收者,依此类推。

案例一:传统模式

学校OA系统的采购审批项目:需求是采购员采购教学器材

  • 如果金额小于等于5000,由教学主任审批(0<=x<=5000)
  • 如果 金额小于等于10000,由院长审批(5000
  • 如果金额小于等于30000,由副校长审批(10000
  • 如果金额超过30000以上,由校长审批( 30000 责任链模式(Chain of Responsibility Pattern)_第1张图片
    传统方案解决OA系统审批问题
  • 传统方式是: 接收到一个采购请求后,根据采购金额来调用对应的Approver (审批人)完成审批。
  • 传统方式的问题分析:客户端这里会使用到分支判断(比如switch) 来对不同的采购请求处理, 这样就存在如下问题
    • 如果各个级别的人员审批金额发生变化,在客户端的也需要变化
    • 客户端必须明确的知道有多少个审批级别和访问
  • 这样对一个采购请求进行处理和Approver (审批人)就存在强耦合关系,不利于代码的扩展和维护

案例二:责任链模式

责任链模式(Chain of Responsibility Pattern)_第2张图片

//请求类
public class PurchaseRequest {
	private int type = 0; //请求类型
	private float price = 0.0f; //请求金额
	private int id = 0;
	//构造器
	public PurchaseRequest(int type, float price, int id) {
		this.type = type;
		this.price = price;
		this.id = id;
	}
	public int getType() { return type; }
	public float getPrice() { return price; }
	public int getId() { return id; }
}
public class DepartmentApprover extends Approver {
	public DepartmentApprover(String name) { super(name); }
	@Override
	public void processRequest(PurchaseRequest purchaseRequest) {
		if(purchaseRequest.getPrice() <= 5000) {
			System.out.println(" 请求编号 id= " + purchaseRequest.getId() + " 被 " + this.name + " 处理");
		}else {
			approver.processRequest(purchaseRequest);
		}
	}
}
public class CollegeApprover extends Approver {
	public CollegeApprover(String name) {super(name); }
	@Override
	public void processRequest(PurchaseRequest purchaseRequest) {
		if(purchaseRequest.getPrice() < 5000 && purchaseRequest.getPrice() <= 10000) {
			System.out.println(" 请求编号 id= " + purchaseRequest.getId() + " 被 " + this.name + " 处理");
		}else {
			approver.processRequest(purchaseRequest);
		}
	}
}
public class ViceSchoolMasterApprover extends Approver {
	public ViceSchoolMasterApprover(String name) { super(name); }
	@Override
	public void processRequest(PurchaseRequest purchaseRequest) {
		if(purchaseRequest.getPrice() < 10000 && purchaseRequest.getPrice() <= 30000) {
			System.out.println(" 请求编号 id= " + purchaseRequest.getId() + " 被 " + this.name + " 处理");
		}else {
			approver.processRequest(purchaseRequest);
		}
	}
}
public class SchoolMasterApprover extends Approver {
	public SchoolMasterApprover(String name) {super(name); }
	@Override
	public void processRequest(PurchaseRequest purchaseRequest) {
		if(purchaseRequest.getPrice() > 30000) {
			System.out.println(" 请求编号 id= " + purchaseRequest.getId() + " 被 " + this.name + " 处理");
		}else {
			approver.processRequest(purchaseRequest);
		}
	}
}
public class Client {
	public static void main(String[] args) {
		//创建一个请求
		PurchaseRequest purchaseRequest = new PurchaseRequest(1, 31000, 1);
		//创建相关的审批人
		DepartmentApprover departmentApprover = new DepartmentApprover("张主任");
		CollegeApprover collegeApprover = new CollegeApprover("李院长");
		ViceSchoolMasterApprover viceSchoolMasterApprover = new ViceSchoolMasterApprover("王副校");
		SchoolMasterApprover schoolMasterApprover = new SchoolMasterApprover("佟校长");
		
		//需要将各个审批级别的下一个设置好 (处理人构成环形: )
		departmentApprover.setApprover(collegeApprover);
		collegeApprover.setApprover(viceSchoolMasterApprover);
		viceSchoolMasterApprover.setApprover(schoolMasterApprover);
		//单向责任链这里可以不加
		schoolMasterApprover.setApprover(departmentApprover);
		
		departmentApprover.processRequest(purchaseRequest);
		viceSchoolMasterApprover.processRequest(purchaseRequest);
	}
}

职责链模式在SpringMVC框架应用的源码分析

SpringMVC-HandlerExecutionChain 类就使用到职责链模式

public class ResponsibilityChain {

	public static void main(String[] args) {
		// DispatcherServlet 
		
		//说明
		/*
		 * 
		 *  protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
		 *   HandlerExecutionChain mappedHandler = null; 
		 *   mappedHandler = getHandler(processedRequest);//获取到HandlerExecutionChain对象
		 *    //在 mappedHandler.applyPreHandle 内部 得到啦 HandlerInterceptor interceptor
		 *    //调用了拦截器的  interceptor.preHandle
		 *   if (!mappedHandler.applyPreHandle(processedRequest, response)) {
					return;
				}
				
			  //说明:mappedHandler.applyPostHandle 方法内部获取到拦截器,并调用 
			  //拦截器的  interceptor.postHandle(request, response, this.handler, mv);
			 mappedHandler.applyPostHandle(processedRequest, response, mv);
		 *  }
		 *  
		 *  
		 *  //说明:在  mappedHandler.applyPreHandle内部中,
		 *  还调用了  triggerAfterCompletion 方法,该方法中调用了  
		 *  HandlerInterceptor interceptor = getInterceptors()[i];
			try {
				interceptor.afterCompletion(request, response, this.handler, ex);
			}
			catch (Throwable ex2) {
				logger.error("HandlerInterceptor.afterCompletion threw exception", ex2);
			}
		 */
	
	}

}
 protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HandlerExecutionChain mappedHandler = null;
        //获取到HandlerExecutionChain对象
        mappedHandler = this.getHandler(processedRequest);
       	//调用了拦截器的  interceptor.preHandle
		if (!mappedHandler.applyPreHandle(processedRequest, response)) {
                        return;
                    }

        mappedHandler.applyPostHandle(processedRequest, response, mv);
 }

applyPostHandle

		//说明:mappedHandler.applyPostHandle 方法内部获取到拦截器,并调用 
	    //拦截器的  interceptor.postHandle(request, response, this.handler, mv);
	void applyPostHandle(HttpServletRequest request, HttpServletResponse response, ModelAndView mv) throws Exception {
		if (getInterceptors() == null) {
			return;
		}
		for (int i = getInterceptors().length - 1; i >= 0; i--) {
			HandlerInterceptor interceptor = getInterceptors()[i];
			interceptor.postHandle(request, response, this.handler, mv);
		}
	}
//说明:在  mappedHandler.applyPreHandle内部中,还调用了  triggerAfterCompletion 方法,该方法中调用了  
	boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (getInterceptors() != null) {
			for (int i = 0; i < getInterceptors().length; i++) {
				HandlerInterceptor interceptor = getInterceptors()[i];
				if (!interceptor.preHandle(request, response, this.handler)) {
					triggerAfterCompletion(request, response, null);
					return false;
				}
				this.interceptorIndex = i;
			}
		}
		return true;
	}

triggerAfterCompletion

	void triggerAfterCompletion(HttpServletRequest request, HttpServletResponse response, Exception ex)
			throws Exception {

		if (getInterceptors() == null) {
			return;
		}
		for (int i = this.interceptorIndex; i >= 0; i--) {
			HandlerInterceptor interceptor = getInterceptors()[i];
			try {
				interceptor.afterCompletion(request, response, this.handler, ex);
			}
			catch (Throwable ex2) {
				logger.error("HandlerInterceptor.afterCompletion threw exception", ex2);
			}
		}
	}

源码总结

  • springmvc 请求的流程图中,执行了拦截器相关方法interceptor.preHandler 等等
  • 在处理SpringMvc请求时,使用到职责链模式还使用到适配器模式
  • HandlerExecutionChain主要负责的是请求拦截器的执行和请求处理,但是他本身不处理请求,只是将请求分配给链上注册处理器执行,这是职责链实现方式,减少职责链本身与处理逻辑之间的耦合,规范了处理流程
  • HandlerExecutionChain 维护了HandlerInterceptor 的集合,可 以向其中注册相应的拦截器.

总结

  • 将请求和处理分开,实现解耦,提高系统的灵活性
  • 简化了对象,使对象不需要知道链的结构
  • 性能会受到影响,特别是在链比较长的时候,因此需控制链中最大节点数量,一般通过在Handler中设置一个最大节点数量,在setNext()方法中判断是否已经超过阀值,超过则不允许该链建立,避免出现超长链无意识地破坏系统性能
  • 调试不方便。采用了类似递归的方式,调试时逻辑可能比较复杂
  • 最佳应用场景:有多个对象可以处理同一个请求时,比如:多级请求、请假/加薪等审批流程、JavaWeb中Tomcat对Encoding的处理、拦截器

你可能感兴趣的:(7大原则和23种设计模式,责任链模式,java,开发语言)