4 Combining Strategy Design Pattern and Chain of Responsibility Design Pattern

0 25
Author: Jingdong Logistics, Zhong Lei1 IntroductionWhile sorting out the interfa...

Author: Jingdong Logistics, Zhong Lei

1 Introduction

While sorting out the interface logic recently, the strategy and chain of responsibility design patterns used in the code left a very deep impression on me. A business logic process is usually very suitable for implementing the chain of responsibility and strategy design patterns, because a business requirement can usually be divided into individual independent logic processing units and combined in sequence, and the chain of responsibility design pattern can well link the entire business process, while the strategy design pattern can extract the changing algorithm part in the business, thus reusing the main common logic and allowing flexible replacement of business algorithms. Using these two design patterns can flexibly expand our code to adapt to different business requirements. Since these two design patterns are very practical, I will briefly introduce my understanding of them and their application in the Spring framework source code below.

11: 2 General Definition of Chain of Responsibility Design Pattern

The Chain of Responsibility design pattern is a behavioral design pattern in the design patterns. Its basic structure is similar to a chain, where the entire chain is composed of individual links. Each link in the program code is an independent processing unit, each of which has its own unique logic. When a processing request arrives at this chain, it will pass through each processing unit in turn until the request is processed completely.

9: 2.1 Use Case:

8: A business request needs to be processed by a group of processing units. This scenario is similar to setting multiple functional processing units in a business logic process, where a business request needs to be processed in series by these multiple processing units.

1676972409_63f49179531d30ff6c55a.png!small?1676972409985

7: In the program, there are multiple processing units that can handle the same request, but the specific processing unit to be used needs to be dynamically determined at runtime based on the request.

1676972427_63f4918b8f716e74153cb.png!small?1676972428260

2.2 Class Diagram Structure and Application in Spring AOP Framework

3.2 Class Diagram Structure and Application in Spring Framework

1676972446_63f4919eabcc2877be107.png!small?1676972447782

2: Application of Chain of Responsibility Design Pattern in Spring AOP Framework

The AOP module in the Spring framework uses the Chain of Responsibility design pattern to wrap the process of a single method call into a method call chain to enhance the target method. The Spring AOP module includes five types of advice methods: Before, After, AfterReturning, AfterThrowing, and Around. The Spring AOP module wraps these advice methods and the target method into a call chain through dynamic proxy to fulfill the processing logic of each notification module. The following is a source code analysis diagram of Spring AOP.

1676972466_63f491b24d10bcf516476.png!small?1676972467047

Spring AOP implements the functionality of the Chain of Responsibility by recursion. First, it sorts all the advice methods, and then uses a List index to control the start and end of the entire execution process. In the entire Chain of Responsibility, the Before advice is responsible for executing the preprocessing, the After advice is responsible for executing the post-processing, the AfterReturning method is responsible for executing the processing logic after the target method successfully returns, and the AfterThrowing method is responsible for executing the processing logic after the target method throws an exception. Spring AOP wraps the advice methods into each node of the method call chain,巧妙地 utilizing the Chain of Responsibility pattern to complete the enhancement of the target method.

3: Generalized Chain of Responsibility Design Pattern

In the process of writing daily code, the Chain of Responsibility design pattern does not necessarily require such a strict structure. As long as the overall process of the code is composed of individual processing units and combined in a certain order, it can also be regarded as a more generalized Chain of Responsibility design pattern, which can also well satisfy the Open-Closed Principle. For example, the following is a more commonly used code structure.

1676972483_63f491c367bd07f24e42b.png!small?1676972484438

上面这种结构同样也能实现责任链处理功能,也可以更加简洁的进行编写,同样可以很好的进修改和灵活扩展,在维护代码的适合也会更加清晰。

This kind of structure can also realize the responsibility chain processing function, can be written more concisely, and can also be well modified and flexibly extended. It will also be clearer in maintaining the code.

2 Advantages of Responsibility Chain Pattern:

1. Each processing node has its own unique processing logic, clearly defining the responsibilities in the entire process, and conforms to the single responsibility principle of classes.

2. The responsibility chain can be flexibly changed according to business requirements, dynamically adjusted and plugged in, satisfying the important open and closed principle.

3. It reduces the coupling degree between the request sender and the request handler.

3 General Definition of Strategy Design Pattern

The strategy design pattern is also a behavioral design pattern in the design patterns. Its structural representation is to isolate the variable algorithm strategy part from the business code logic, forming a strategy pool, so that it can be replaced and updated at any time, making our code structure more flexible and easier to extend.

3.1 Use Cases

1676972535_63f491f7c6e9cd389cb18.png!small?1676972537143

1: When the code needs to choose different business algorithms according to the context logic, we can use the strategy design pattern to optimize the code judgment structure, thus avoiding a large number of if/else branch judgments.

1676972547_63f492037ef980f4ef12e.png!small?1676972548793

2: When the main processing logic of the code is roughly the same, but there are differences in some business algorithms, these different business algorithms can be extracted to avoid a lot of repetitive code writing and to reuse the main code logic.

3.2 Class Diagram Structure and Application in Spring Framework

1676972566_63f49216065dfbc67b4df.png!small?1676972567090

1: Class Diagram Structure

2: Application in Spring FrameworkBeanPostProcessorThere are many extension strategies left by the Spring framework for developers, which realize the function of dynamic plug-in and extension. One typical extension strategy isBeanPostProcessorinterface,BeanPostProcessorThe interface allows us to perform some logical processing strategies before and after the initialization of the Bean to change the properties of the Bean, allowing us to modify and personalize the Bean. Spring AOP utilizes

1676972586_63f4922aed32ed4c1d968.png!small?1676972587516

Spring AOP extends this strategy extension point to create dynamic proxy Beans, and the following is the source code analysis of the Spring AOP post-processor.AspectJAwareAdvisorAutoProxyCreatorThis implementsBeanPostProcessorThe post-processor of the interface created a dynamic proxy class after the Bean initialization, which inpostProcessAfterInitaliztionmethodWarpIfNecessaryThe proxy class creation is implemented in the Chinese method. The Spring framework utilizes this template plus strategy design pattern to allow us to personalize the extension of the framework's functions, making the framework very flexible and extensible. We can also add our own according to business requirements.BeanPostProcessorStrategy to implement its unique logic, which well satisfies the important open-closed design principle.

3: Generalized Strategy Design Pattern

Similarly, we do not have to strictly follow the definition of the strategy design pattern to write code. As long as the main business logic remains unchanged, extract the changing parts, and form a strategy idea that can be expanded as needed. Below, we will illustrate this more generalized strategy pattern with the source code of SpringBoot's automatic assembly. The SpringBoot automatic assembly mechanism dynamically loads the classes we need to use according to the current code running environment and the **@Conditional** annotation. This strategy design pattern is a more generalized strategy design pattern that also meets the design principle of on-demand selection and dynamic insertion. The principle of SpringBoot's automatic assembly mechanism is as follows:

SpringBoot in **@EnableAutoConfigurationAnnotation uses@import**Annotation imported
EnableAutoConfigurationImportSelectorclass.

1676972604_63f4923ccf041c4a8cd83.png!small?1676972605830

UtilizingEnableAutoConfigurationImportSelectorof the classselectImportsMethods to load the class configured in the META-INF/spring.factories file in the jar package.

1676972622_63f4924e05d028f0bbb87.png!small?1676972622816

1676972636_63f4925cb07f8cadfbdfd.png!small?1676972637306

Finally, combine various **@Conditional** annotations to implement the strategy design pattern that loads as needed.

1676972651_63f4926b3f15997652ced.png!small?1676972651981

The strategy design idea of SpringBoot, which automatically assembles as needed, does not strictly conform to the structure of the strategy design pattern in terms of structure, but its overall design idea is very consistent with the strategy design pattern. We can also flexibly switch the strategy algorithms used in our code through configuration files in our projects.

3.3 Advantages of Strategy Design Pattern:

1: Independent business algorithms can be dynamically selected and switched during program execution.

2: Separate the variable business algorithms from the main business logic, achieving more flexible maintenance and expansion.

3: Satisfy the open-closed principle, without modifying the original code logic, different business algorithms can be flexibly switched.

4 Combining Strategy Design Pattern and Chain of Responsibility Design Pattern

Combining the strategy design pattern and the chain of responsibility design pattern can form a flexible and scalable process structure, which can meet various business needs. Below is the structure diagram combining both patterns.

1676972667_63f4927b92f1dc5f04815.png!small?1676972668500

A request, when processed by each handler unit, selects an appropriate strategy based on the context content of the request and then links all the handlers together to form a complete business process.

5 Summary

In the process of writing daily code, the changes in business requirements are always unpredictable, which may lead to frequent adjustments of our code in line with the changes in requirements. If we are not careful, our code may become very bulky and complex, and it may become difficult to maintain after accumulating to a certain degree. At this point, using appropriate code design patterns in advance can effectively alleviate this situation. The responsibility chain and strategy design patterns described in the text can effectively meet the open-closed principle of code writing and can better respond to the changing business requirements at any time.

你可能想看:

Announcement regarding the addition of 7 units as technical support units for the Ministry of Industry and Information Technology's mobile Internet APP product security vulnerability database

It is possible to perform credible verification on the system boot program, system program, important configuration parameters, and application programs of computing devices based on a credible root,

Dubbo Architecture Design and Source Code Analysis (Part Three) Chain of Responsibility Pattern

d) Adopt identification technologies such as passwords, password technologies, biometric technologies, and combinations of two or more to identify users, and at least one identification technology sho

Distributed Storage Technology (Part 2): Analysis of the architecture, principles, characteristics, and advantages and disadvantages of wide-column storage and full-text search engines

b) It should have the login failure handling function, and should configure and enable measures such as ending the session, limiting the number of illegal logins, and automatically exiting when the lo

b) It should have a login failure handling function, and should configure and enable measures such as ending the session, limiting the number of illegal login attempts, and automatically logging out w

In today's rapidly developing digital economy, data has become an important engine driving social progress and enterprise development. From being initially regarded as part of intangible assets to now

In-depth Analysis: Mining Trojan Analysis and Emergency Response Disposal Under a Complete Attack Chain

Different SRC vulnerability discovery approach: Practical case of HTTP request splitting vulnerability

最后修改时间:
admin
上一篇 2025年03月26日 00:29
下一篇 2025年03月26日 00:52

评论已关闭