Chain of Responsibility Pattern (Chain of Responsibility Pattern)

Purchasing approval items of school OA system: The requirements are

Purchasers purchase teaching equipment

  1. If the amount is less than or equal to 5000, it will be approved by the teaching director (0<=x<=5000)

  2. If the amount is less than or equal to 10000, it shall be approved by the dean (5000<x<=10000)

  3. If the amount is less than or equal to 30000, it will be approved by the vice principal (10000<x<=30000)

  4. If the amount is more than 30,000, there is approval by the principal (30000<x)
    , please design the procedure to complete the procurement approval project

Traditional solution to OA system approval, traditional design solution (class diagram)

Insert picture description here

Analysis of traditional solutions to OA system approval problems

  1. The traditional way is: after receiving a purchase request, call the corresponding Approver (approver) to complete the approval according to the purchase amount.

  2. Traditional way of problem analysis: The client will use branch judgments (such as switch) to process different purchase requests, so there are the following problems
    (1) If the approval amount of personnel at various levels changes, the client also needs to change
    (2) The client must clearly know how many approval levels and access there are

  3. In this way, there is a strong coupling relationship between processing a purchase request and Approver, which is not conducive to code expansion and maintenance

  4. Solution=》Responsibility Chain Model

Basic introduction to the chain of responsibility model

basic introduction

  1. The Chain of Responsibility Pattern (Chain of Responsibility Pattern), also known as the Chain of Responsibility Pattern, creates a chain of recipient objects for the request (simple diagram). This mode decouples the sender and receiver of the request.

  2. The chain of responsibility pattern usually contains a reference to another recipient for each recipient. If an object cannot handle the request, it will pass the same request to the next recipient, and so on.

  3. This type of design pattern is a behavioral pattern

Principle class diagram of the chain of responsibility pattern

Insert picture description here
 Description of the principle class diagram-namely (role and responsibility of the chain of responsibility model)

  1. Handler : Abstract handler, defines an interface for processing requests, and also means another Handler

  2. ConcreteHandlerA , B It is a specific processor that processes the request for which it is responsible, can access its successor (ie the next processor), if it can handle the current request, then process it, otherwise it will hand over the request to a successor to process, thus forming A chain of responsibility

  3. Request , Meaning many attributes, representing a request

Responsibility chain model solves OA system procurement approval

  1. Application example requirements
    Write procedures to complete the procurement approval project of the school OA system: demand
    purchasers purchase teaching equipment.
    If the amount is less than or equal to 5000, it is approved by the teaching director.
    If the amount is less than or equal to 10,000, it is approved by the dean.
    If the amount is less than or equal to 30,000, it is approved by the vice principal.
    If the amount exceeds 30,000, the principal will approve
  2. Idea analysis and illustration (class diagram)
    Insert picture description here
  3. Code

Client

public class Client {
    
    

	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		//创建一个请求
		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);
	}

}

Request class

//请求类
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;
	}
	
}

Abstract processing class

public abstract class Approver {
    
    

	Approver approver;  //下一个处理者
	String name; // 名字
	
	public Approver(String name) {
    
    
		// TODO Auto-generated constructor stub
		this.name = name;
	}

	//下一个处理者
	public void setApprover(Approver approver) {
    
    
		this.approver = approver;
	}
	
	//处理审批请求的方法,得到一个请求, 处理是子类完成,因此该方法做成抽象
	public abstract void processRequest(PurchaseRequest purchaseRequest);
	
}

Specific treatment

public class ViceSchoolMasterApprover extends Approver {
    
    

	public ViceSchoolMasterApprover(String name) {
    
    
		// TODO Auto-generated constructor stub
		super(name);
	}
	
	@Override
	public void processRequest(PurchaseRequest purchaseRequest) {
    
    
		// TODO Auto-generated method stub
		if(purchaseRequest.getPrice() < 10000 && purchaseRequest.getPrice() <= 30000) {
    
    
			System.out.println(" 请求编号 id= " + purchaseRequest.getId() + " 被 " + this.name + " 处理");
		}else {
    
    
			approver.processRequest(purchaseRequest);
		}
	}
}

Source code analysis of the chain of responsibility pattern in the SpringMVC framework

  1. The SpringMVC-HandlerExecutionChain class uses the responsibility chain mode

  2. SpringMVC request flow diagram

  3. Code analysis + Debug source code + description

  4. Source code and description

import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerInterceptor;
public class ResponsibilityChain {
    
    
public static void main(String[] args) {
    
    
// TODO Auto-generated method stub
// 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);
}
*/
}
}
  1. Summary of the source code
     In the flow chart of the springmvc request, the interceptor-related methods interceptor.preHandler, etc. are executed
     When processing SpringMvc requests, the responsibility chain mode is used and the adapter mode is used
     HandlerExecutionChain is mainly responsible for the execution of the request interceptor And request processing, but he does not process the request itself, but only assigns the request to the chain registration processor for execution. This is the implementation of the responsibility chain, which reduces the coupling between the responsibility chain itself and the processing logic, and standardizes the processing flow
     HandlerExecutionChain is maintained A collection of HandlerInterceptor, to which the corresponding interceptor can be registered.

Notes and details of the chain of responsibility model

  1. Separate request and processing, realize decoupling, and improve system flexibility

  2. Simplify the object so that the object does not need to know the structure of the chain

  3. Performance will be affected, especially when the chain is relatively long , so you need to control the maximum number of nodes in the chain. Generally, you can set a maximum number of nodes in the Handler and judge whether the threshold has been exceeded in the setNext() method. Allow the chain to be established,Avoid unintentionally destroying system performance by super long chains

  4. Inconvenient debugging. Using a similar recursion method, the logic may be more complicated when debugging

  5. Best application scenario: When there are multiple objects that can handle the same request, such as: multi-level requests, leave/pay raises and other approval processes, Tomcat's processing of Encoding in Java Web, interceptors

to sum up

Abstract classes aggregate themselves.
Concrete subclasses will be like linked lists.

Guess you like

Origin blog.csdn.net/weixin_46168350/article/details/111502135