Re-learning Java Design Patterns: Actual Adapter Patterns

June 08, 2023 00:09 Read 117

Re-learning Java Design Patterns: Actual Adapter Patterns

foreword

In actual development, we often encounter scenarios where we need to extract specified field values ​​from multiple MQ message bodies. For example, from a JSON message body containing multiple fields, only the value of one of the fields needs to be extracted for subsequent processing. At this time, we can use the adapter pattern to achieve fast and effective data conversion.

This article will start from the actual scene and introduce the concept, characteristics, advantages and disadvantages of the adapter pattern and its specific implementation in Java. And it shows how to use the adapter mode to extract specified field values ​​from multiple MQ message bodies through actual combat cases.

What is the adapter pattern

Adapter mode is a structural design mode, its function is to convert the interface of a class into another interface expected by the client, so as to achieve the purpose of decoupling. The adapter mode is usually used for the adaptation of existing classes, or when the interfaces of multiple classes are incompatible, the cooperation between them is completed through the adapter.

The adapter pattern usually includes three roles:

  1. Target interface: The interface expected by the client, that is, the interface that the client wants to call.
  2. Adapter (Adapter): responsible for converting the source interface to the target interface. Adapters usually include a reference to a target interface, and an instance object of a source interface.
  3. Source interface (Adaptee): An existing class or object whose interface is incompatible with the target interface and needs to be converted to the target interface by the adapter.

Features of the adapter pattern

The biggest feature of the adapter mode is decoupling, which can decouple the client from the source interface, thereby realizing the transparency of the source interface, so that the client does not need to know the specific implementation details of the source interface.

In addition, the adapter mode also has the following characteristics:

  • Flexibility: Adapters can dynamically add and replace existing source interfaces to achieve flexibility and scalability.
  • Reusability: Adapters can reuse existing code, reducing the repetition rate of code.
  • Security: Adapters can improve code security by isolating client and source interfaces.

Advantages and disadvantages of the adapter pattern

The advantage of the adapter mode is that it can realize the adaptation between different interfaces, thereby expanding the scope of application of existing interfaces and classes. At the same time, the adapter mode can also improve the code reuse rate and flexibility, and reduce the coupling degree of the code.

The disadvantage of the adapter mode is that it may increase the complexity of the code, especially when the target interface has many methods and adapter methods need to be added, it will increase the difficulty of code maintenance. In addition, too many adapters may affect the performance of the program.

The Concrete Realization of Adapter Pattern in Java

In Java, there are two main implementations of the adapter pattern, namely the class adapter pattern and the object adapter pattern.

class adapter pattern

The class adapter pattern is implemented using inheritance, i.e. the adapter inherits from the source interface and implements the target interface. In this way, the adapter can have the functions of both the source interface and the target interface, thereby converting the source interface to the target interface.

The following is a schematic diagram of the class adapter pattern:

The implementation code of the class adapter pattern in Java is as follows:

 
 

java

copy code

public interface Target { void request(); } public class Adaptee { public void SpecificRequest() { // 原有的业务逻辑 } } public class Adapter extends Adaptee implements Target { // 实现目标接口 @Override public void request() { // 转换源接口并调用方法 this.SpecificRequest(); } }

object adapter pattern

The object adapter pattern is implemented using composition, that is, the adapter holds an instance object of a source interface and implements the target interface. In this way, the adapter can convert the source interface to the target interface by holding the instance object of the source interface.

The implementation code of the object adapter pattern in Java is as follows:

 
 

java

copy code

public interface Target { void request(); } public class Adaptee { public void SpecificRequest() { // 原有的业务逻辑 } } public class Adapter implements Target { private Adaptee adaptee; public Adapter(Adaptee adaptee) { this.adaptee = adaptee; } // 实现目标接口 @Override public void request() { // 转换源接口并调用方法 this.adaptee.SpecificRequest(); } }

Practical case: Extract specified field values ​​from multiple MQ message bodies

In actual development, we often need to extract specified field values ​​from multiple MQ message bodies, such as extracting the value of a certain field from a JSON message body. At this point, we can use the adapter pattern to handle the scenario.

The following is a practical case of extracting specified field values ​​from multiple JSON message bodies:

 
 

java

copy code

public interface Extractor { String extract(JSONObject json); } public class UserIdExtractor implements Extractor { @Override public String extract(JSONObject json) { return json.getString("userId"); } } public class UserNameExtractor implements Extractor { @Override public String extract(JSONObject json) { return json.getString("userName"); } } public class FieldExtractorAdapter implements Extractor { private Extractor extractor; public FieldExtractorAdapter(Extractor extractor) { this.extractor = extractor; } @Override public String extract(JSONObject json) { return this.extractor.extract(json.getJSONObject("data")); } }

In the above code, Extractor is the abstract interface, which defines the method of extracting fields from the JSON message body, UserIdExtractor and  is the concrete implementation class, which is used to extract  and  UserNameExtractor from the JSON message body respectively  .  It is the adapter class, which implements   the interface and holds an instance of the concrete implementation class. By calling the method of the concrete implementation class, the source interface is adapted to the target interface.userIduserNameFieldExtractorAdapterExtractor

Next, we can call it through the following code  FieldExtractorAdapter:

 
 

java

copy code

public static void main(String[] args) { String jsonString = "{\"data\": {\"userId\": \"123\", \"userName\": \"Tom\"}}"; JSONObject json = JSONObject.parseObject(jsonString); Extractor userIdExtractor = new FieldExtractorAdapter(new UserIdExtractor()); Extractor userNameExtractor = new FieldExtractorAdapter(new UserNameExtractor()); String userId = userIdExtractor.extract(json); String userName = userNameExtractor.extract(json); System.out.println("userId: " + userId + ", userName: " + userName); }

The output is as follows:

 
 

yaml

copy code

userId: 123, userName: Tom

Summarize

The adapter pattern is a structural design pattern with a wide range of application scenarios. The adapter mode can realize the adaptation between different interfaces, thereby expanding the application range of existing interfaces and classes. At the same time, the adapter mode can also improve the code reuse rate and flexibility, and reduce the coupling degree of the code.

In Java, there are two main implementations of the adapter pattern, namely the class adapter pattern and the object adapter pattern. The specific implementation can be flexibly selected according to actual needs.

Finally, we introduced how to use the adapter pattern to extract specified field values ​​from multiple MQ message bodies through a practical case. Adapter mode has a wide range of applications in actual development, helping us to quickly and efficiently realize the adaptation between different interfaces.

Guess you like

Origin blog.csdn.net/BASK2312/article/details/131110618