Home Java javaTutorial First introduction to Java design pattern Adapter pattern

First introduction to Java design pattern Adapter pattern

Jan 19, 2017 pm 04:12 PM

[Text]

We know that the most important and most difficult to use UI control in Android is the ListView list control, and if you want to use it flexibly, you must use an adapter, so , I think it is still necessary to learn the adapter pattern in Java (regardless of whether it can be used in the future). After all, the Java language is a very important foundation for Android development.

Completely understand the adapter pattern, there is a lot of knowledge to learn, for example: the adapter pattern has two different forms: class adapter pattern and object adapter pattern. But as a beginner, I will simply learn the introductory knowledge of orchestration mode, and I will continue to improve it in the future. I hope that the children who are struggling on the road of coding will not complain →_→

1. Adapter introduction

•Convert the interface of a class into another interface that the customer wants. The Adapter pattern enables classes to work together that would otherwise not work together due to incompatible interfaces.
•The adapter pattern is very commonly used in modern Java frameworks. This mode is suitable for the following scenarios: you want to use an existing class, but the class does not meet the interface requirements; or you need to create a reusable class that adapts to other classes that do not provide a suitable interface.

2. Examples of Apples and Oranges

The idea of ​​an adapter can be illustrated through the following simple example. This example wants an orange to be "fitted" into an apple. As shown in the figure below:

First introduction to Java design pattern Adapter pattern

#As you can see in the lower half of the figure above, the adapter contains an Orange instance and inherits the Apple class. The orange object is placed in the adapter, so the orange behaves like an apple. The corresponding logic diagram is as follows:

First introduction to Java design pattern Adapter pattern

3. Example of socket box plug

First introduction to Java design pattern Adapter pattern

In the above figure, we can pass The adapter in the middle allows the plug on the right to connect successfully to the socket on the left.

4. Code implementation of plug adapter

/**
  适配器模式( Adapter ):将一个类的接口转换成客户希望的另外一个接口。
  适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
*/
class AdapterDemo{
  public static void main(String[] args){
    //电源A开始工作
    PowerA powerA = new PowerAImpl();
    start(powerA);
    PowerB powerB = new PowerBImpl();
    PowerAAdapter pa = new PowerAAdapter(powerB);
    start(pa);
  }
  //定义方法:电源A工作
  public static void start(PowerA powerA){
    System.out.println("....一些重复的代码.....");
    powerA.insert();
    System.out.println("....一些重复的代码.....\n");
  }
 
  /**
  public static void start(PowerB powerB){
    System.out.println("....一些重复的代码.....");
    powerB.connect();
    System.out.println("....一些重复的代码.....");
  }
  */
}
//定义适配器类
class PowerAAdapter implements PowerA{
  private PowerB powerB;//要进行适配的接口
   
  public PowerAAdapter(PowerB powerB){
    this.powerB = powerB;
  }
  //实现接口PowerA,则必然要实现PowerA里面的方法
  public void insert(){
    powerB.connect();
  }
}
/**
  电源A接口
*/
interface PowerA{
  public void insert();
}
class PowerAImpl implements PowerA{
  public void insert(){
    System.out.println("电源A接口插入,开始工作");
  }
}
/**
  电源B接口
*/
interface PowerB{
  public void connect();
}
class PowerBImpl implements PowerB{
  public void connect(){
    System.out.println("电源B接口已连接,开始工作");
  }
}
Copy after login

In this example, we want PowerB to call the code in the Start() method in PowerA; of course, we don’t want to write it repeatedly Lines 23 and 25 of code that were commented out. At this time, you can use the adapter mode.

Explanation of the above code:

Line 30: Start defining the adapter, which is also the beginning of the core code;

Lines 33 and 34 : Pass PowerB in through the construction method;

Line 37: Since the interface PowerA is implemented, the method insert() in PowerA must be implemented;

Line 38 of code: We call PowerB's connect() method in PowerA's insert() method;

Then, the 10th, 11th, and 12th lines of code mean: in new When a PowerB is generated, we pass it to the adapter PowerAAdapter, start the adapter, and then PowerB will execute the code on lines 16, 24, and 18.

Note: The order of 16, 24, and 18 is not wrong, because we have replaced the 24th line of code with the 17th line of code in the adapter.

The operation effect is as follows:

First introduction to Java design pattern Adapter pattern

#Similarly, if I also want to use PowerA as PowerB, I can define another adapter PowerBAdapter to achieve Bidirectional adapter.

5. Summary

The commented out lines 23 and 25 above indicate a lot of repeated code, which does not conform to the object-oriented way of thinking. Let's now imagine an example: Our project has been online and is being used by customers, but then some new requirements have been added. There is an OO principle for object-oriented: closed to modification (try not to modify the code after it goes online, otherwise a chain reaction may occur, causing problems in other codes that call the method here), and open to extension (new code defined by yourself) The method has not been called by others, of course we can modify it). At this point, we can reduce these repeated codes through adapters.

6. OO design principles

•Interface-oriented programming (abstraction-oriented programming)
•Encapsulation changes
•Use more combination and less inheritance
•Close for modifications and open for extensions

Personally feel that these design principles need to be continuously deepened in practice, so I won’t describe them too much here~

The above is the entire content of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support the PHP Chinese website.

For more articles related to the Java design pattern adapter pattern, please pay attention to the PHP Chinese website!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

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 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...

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 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...

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 elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

See all articles