search
HomeJavajavaTutorialExample analysis of chain of responsibility pattern in Java design patterns

Example analysis of chain of responsibility pattern in Java design patterns

Aug 10, 2017 pm 01:27 PM
javaCase AnalysisDesign Patterns

This article mainly introduces the relevant information of the responsibility connection model of the design pattern in detail, which has certain reference value. Interested friends can refer to it

Definition:Allow multiple objects to have the opportunity to process the request, thus 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:

##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 business logic of the code 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 If i==1, it will be processed by Handler1, if i==2, it will be processed by Handler2, 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 as simple as judging whether it is 1 or 2. It may require complex calculations, querying the database, etc., which will require a lot of extra code. If If there are too many judgment conditions, then this if...else...statement will basically become unreadable.
High degree of coupling: If we want to continue to add classes for processing requests, then we must continue to add else if judgment conditions; in addition, the order of this condition judgment is also hard-coded , if you want to change the order, you can only modify this conditional statement.

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 chain of responsibility pattern

The class diagram of the chain of responsibility pattern is very simple. It consists of an abstract processing class and a set of its Implementation class composition:


Abstract processing class: The abstract processing class mainly includes a member variable nextHandler that points to the next processing class and a processing request Method handRequest, 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.

                                                                                                                                                            ’s that being that Level class in the code is a simulation are easier to understand if we look at the code:


##

class Level { 
  private int level = 0; 
  public Level(int level){ 
    this.level = level; 
  }; 
   
  public boolean above(Level level){ 
   if(this.level >= level.level){ 
      return true; 
    } 
    return false; 
  } 
} 
 
class Request { 
  Level level; 
  public Request(Level level){ 
    this.level = level; 
  } 
   
  public Level getLevel(){ 
    return level; 
  } 
} 
 
class Response { 
 
} 

abstract class Handler { 
  private Handler nextHandler;   
  public final Response handleRequest(Request request){ 
    Response response = null; 
     
   if(this.getHandlerLevel().above(request.getLevel())){ 
      response = this.response(request); 
    }else{ 
      if(this.nextHandler != null){ 
        this.nextHandler.handleRequest(request); 
      }else{ 
        System.out.println("-----没有合适的处理器-----"); 
      } 
    } 
    return response; 
  } 
  public void setNextHandler(Handler handler){ 
   this.nextHandler = handler; 
  } 
  protected abstract Level getHandlerLevel(); 
   public abstract Response response(Request request); 
} 
 
class ConcreteHandler1 extends Handler { 
  protected Level getHandlerLevel() { 
    return new Level(1); 
  } 
  public Response response(Request request) { 
    System.out.println("-----请求由处理器1进行处理-----"); 
    return null; 
  } 
} 
 
class ConcreteHandler2 extends Handler { 
  protected Level getHandlerLevel() { 
    return new Level(3); 
  } 
  public Response response(Request request) { 
    System.out.println("-----请求由处理器2进行处理-----"); 
    return null; 
  } 
} 
 
class ConcreteHandler3 extends Handler { 
  protected Level getHandlerLevel() { 
    return new Level(5); 
  } 
  public Response response(Request request) { 
    System.out.println("-----请求由处理器3进行处理-----"); 
    return null; 
  } 
} 
 
public class Client { 
  public static void main(String[] args){ 
    Handler handler1 = new ConcreteHandler1(); 
    Handler handler2 = new ConcreteHandler2(); 
    Handler handler3 = new ConcreteHandler3(); 
 
    handler1.setNextHandler(handler2); 
    handler2.setNextHandler(handler3); 
     
    Response response = handler1.handleRequest(new Request(new Level(4))); 
  } 
}

Judgment conditions; Request and Response respectively correspond to requests and responses; the abstract class Handler is mainly used to judge conditions. A processing level is simulated here. Only the processing level of the processing class is higher than the level of Request can be processed, otherwise it will be handed over to the next processor. . Set the chain's before and after execution relationship in the Client class, and hand the request to the first processing class during execution. This is the responsibility chain mode. The function it completes is the same as the if...else... statement in the previous article.


Advantages and Disadvantages of Responsibility Chain Model


Comparing with if...else..., the responsibility chain model has lower coupling because It distributes conditional judgments into various processing classes, and the priority processing order of these processing classes can be set at will. 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 Responsibility Chain Model

Just like the initial example, if you feel inadequate when using if...else...statements to organize a chain of responsibility, When your code looks bad, use the Chain of Responsibility pattern to refactor it.


Summarize

The chain of responsibility model is actually a flexible version of the 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.

The above is the detailed content of Example analysis of chain of responsibility pattern in Java design patterns. For more information, please follow other related articles on the PHP Chinese website!

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
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment