Home >Java >javaTutorial >Examples to explain the application of the chain of responsibility pattern in Java design pattern programming

Examples to explain the application of the chain of responsibility pattern in Java design pattern programming

高洛峰
高洛峰Original
2017-01-19 17:04:251406browse

Definition: Allow multiple objects to have the opportunity to process requests, thereby avoiding the coupling relationship between the sender and receiver of the request. These objects are connected into a chain and the request is passed along the chain until an object handles it.
Type: Behavioral class pattern
Class diagram:

Examples to explain the application of the chain of responsibility pattern in Java design pattern programming

First look at a piece of code:

public void test(int i, Request request){
  if(i==1){
    Handler1.response(request);
  }else if(i == 2){
    Handler2.response(request);
  }else if(i == 3){
    Handler3.response(request);
  }else if(i == 4){
    Handler4.response(request);
  }else{
    Handler5.response(request);
  }
}

The code The business logic is as follows. The method has two parameters: an integer i and a request. The value of i determines who will handle the request. If i==1, it will be handled by Handler1. If i==2, it will be handled by Handler2. to process, and so on. In programming, this method of handling business is very common. All classes that handle requests have if...else...conditional judgment statements connected to form a chain of responsibility to process the request. I believe everyone uses it often. The advantage of this method is that it is very intuitive, simple and clear, and relatively easy to maintain. However, this method also has several troublesome problems:
Bloated code: The judgment conditions in actual applications are usually not so simple. Determining whether it is 1 or 2 may require complex calculations, querying the database, etc., which will require a lot of extra code. If there are more judgment conditions, then this if...else... statement will basically not work. Saw it.
High degree of coupling: If we want to continue to add classes for processing requests, we must continue to add else if judgment conditions; in addition, the order of this condition judgment is also hard-coded. If we want to change the order, we can only modify this Conditional statements.
Now that we are clear about the shortcomings, we must find ways to solve them. The business logic of this scenario is very simple: if condition 1 is met, it will be processed by Handler1, if not, it will be passed down; if condition 2 is met, it will be processed by Handler2, if it is not met, it will continue to be passed down, and so on, until The condition ends. In fact, the improvement method is also very simple, which is to put the judgment condition part into the processing class. This is the principle of the responsibility chain model.

The structure of the responsibility chain pattern
The class diagram of the responsibility chain pattern is very simple. It consists of an abstract processing class and a set of its implementation classes:
Abstract processing class: In the abstract processing class It mainly contains a member variable nextHandler that points to the next processing class and a method handRequest for processing requests. The main idea of ​​the handRequest method is that if the processing conditions are met, this processing class will handle it, otherwise it will be handled by nextHandler.
Specific processing class: The specific processing class mainly implements specific processing logic and applicable conditions for processing.
Example

The chain of responsibility model has two roles:
Abstract handler (Handler) role: defines a requested interface. If necessary, you can define a method to set and return a reference to the next object.
ConcreteHandler (ConcreteHandler) role: If it can be processed, the request will be processed. If it cannot be processed, the request will be passed to the next party for processing. This means that it handles the requests it can handle and has access to its next home.
The test code for the above mode is as follows:

package chainOfResp;
/**
 *描述:抽象处理角色
 */
public abstract class Handler {
 
 protected Handler successor;
 /**
  *描述:处理方法
  */
 public abstract void handlerRequest(String condition);
  
  
 public Handler getSuccessor() {
  return successor;
 }
 public void setSuccessor(Handler successor) {
  this.successor = successor;
 }
  
}
package chainOfResp;
/**
 *描述:具体处理角色
 */
public class ConcreteHandler1 extends Handler {
 
 @Override
 public void handlerRequest(String condition) {
  // 如果是自己的责任,就自己处理,负责传给下家处理
  if(condition.equals("ConcreteHandler1")){
   System.out.println( "ConcreteHandler1 handled ");
   return ;
  }else{
   System.out.println( "ConcreteHandler1 passed ");
   getSuccessor().handlerRequest(condition);
  }
 }
 
}
package chainOfResp;
/**
 *描述:具体处理角色
 */
public class ConcreteHandler2 extends Handler {
  
 @Override
 public void handlerRequest(String condition) {
  // 如果是自己的责任,就自己处理,负责传给下家处理
  if(condition.equals("ConcreteHandler2")){
   System.out.println( "ConcreteHandler2 handled ");
   return ;
  }else{
   System.out.println( "ConcreteHandler2 passed ");
   getSuccessor().handlerRequest(condition);
  }
 }
 
}
package chainOfResp;
/**
 *描述:具体处理角色
 */
public class ConcreteHandlerN extends Handler {
 
 /**
  * 这里假设n是链的最后一个节点必须处理掉
  * 在实际情况下,可能出现环,或者是树形,
  * 这里并不一定是最后一个节点。
  *
  */
 @Override
 public void handlerRequest(String condition) {
 
  System.out.println( "ConcreteHandlerN handled");
   
 }
 
}

package chainOfResp;
/**
 *描述:测试类
 */
public class Client {
 
 /**
  *描述:
  */
 public static void main(String[] args) {
  
  Handler handler1 = new ConcreteHandler1();
  Handler handler2 = new ConcreteHandler2();
  Handler handlern = new ConcreteHandlerN();
   
  //链起来
  handler1.setSuccessor(handler2);
  handler2.setSuccessor(handlern);
   
  //假设这个请求是ConcreteHandler2的责任
  handler1.handlerRequest("ConcreteHandler2");
   
   
 }
 
}

To give an example, in the production workshop of a toy factory, the assembly line is a chain of responsibility. If a toy airplane has a shell assembler , composed of engine assemblers, propeller assemblers, and model packagers. When this object flows to whomever it is, he will be responsible for installing the part he is responsible for. After the installation of this part is completed, it will flow to the next link until all environments are completed. This is a lifelong chain of responsibility. There is also a quality inspection chain, and quality inspection is also divided into multiple parts, including shell inspection, engine inspection, propeller inspection, and packaging inspection. When the product is left to the inspector to inspect the part he is responsible for, if there is a problem, it will be picked up directly. If there is no problem, it will be passed to the next inspector until all inspections are completed. Both are responsibility chains, but the difference is that everyone will handle the generated responsibility chain and handle part of it; while the quality inspection responsibility chain will be judged and either processed or not processed. These are the two classifications of responsibility chains. The latter is called pure responsibility chain, and the former is called impure chain of responsibility. Pure responsibility chain rarely exists in practical applications, and the most common is impure chain of responsibility. The above The model is handled by simulating a pure chain of responsibility.

Advantages and Disadvantages of Responsibility Chain Model
Comparing with if...else..., the responsibility chain mode has lower coupling because it distributes condition determinations into various processing classes, and the priority of these processing classes The processing order can be set arbitrarily. The chain of responsibility model also has shortcomings, which are the same as the shortcomings of if...else... statements, that is, all judgment conditions must be executed before the correct processing class is found. When the chain of responsibility is relatively long, performance problems are more serious. .

Applicable scenarios of the chain of responsibility model
Just like the initial example, if you feel inadequate when using if...else...statements to organize a chain of responsibility and the code looks bad, you can use the chain of responsibility. pattern for reconstruction.

Summary
The responsibility chain model is actually a flexible version of if...else...statement. It puts these judgment condition statements into each processing class. The advantage of this is that it is more flexible, but It also brings risks. For example, when setting up the relationship between processing classes, you must be particularly careful to determine the conditional relationship between the logic before and after processing classes, and be careful not to cause circular references in the chain.

For more examples to explain the application of the chain of responsibility pattern in Java design pattern programming, please pay attention to the PHP Chinese website for related articles!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn