Example analysis of chain of responsibility pattern in Java design 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:
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); } }
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.
The structure of the chain of responsibility pattern
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.
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. .
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.
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.
