Article From:https://www.cnblogs.com/yiRain1992/p/9102217.html

What is the adapter pattern?Converting an interface into another interface that the customer wants, Adapter mode makes those classes that can not work together because the interface is incompatible and work together.

This mode is mainly used to reuse some existing classes, which are correct in data and behavior but not in interfaces.

Adapter pattern structure diagram

 

 

Now, for example, the company sent a technology bull to an American company to participate in a technical exchange, and the technology cow will only be dumb English, indicating that computer English sounds hard. The sponsor was very considerate and gave a translator to the Daniel. In this example, American technical experts explain knowledge equivalent toAn interface that needs to be fitted,The translation here is equivalent toAdapter,Translate English into Chinese so that our company’s understanding is equivalent.The client’s desired interface

The following is the Java code implementation

This is the interface that we want to transform

1 //The interface that customers want is either concrete or abstract, or an interface.
2 abstract class Target{
3     //explain
4     public abstract void interpret();
5 }

American technical expert Balabala

 1 //Classes that need adaptation (American experts explain technical knowledge)
 2 class Adaptee {
 3     //Explanation
 4     private String content ="Speak English";
 5     
 6     public Adaptee(String content){
 7         this.content = content;
 8     }
 9     
10     public void specialInterpret() {
11         System.out.println(content);
12     }
13 
14 }

 

 Translation comes

 1 //Adapters (translation)
 2 class Adapter extends Target{
 3     
 4     private String content = "I'm an American technical expert on Balabala. ";
 5     public Adaptee adaptee = new Adaptee(content);//Build a Adaptee and package it as we want it to be.
 6     @Override
 7     public void interpret() {//Call interpret () on the surface, actually specialInterpret ().
 8         adaptee.specialInterpret();
 9     }
10     
11 }

 

Client test code:

1 public class AdapterTest {
2     public static void main(String[] args) {
3         Target target = new Adapter();
4         target.interpret();//For the client, the interpret () of target is called.
5     }
6  
7 }

 

Look at the running results

 

Summary: adapter mode is mainly used for ready-made classes and interfaces, but the interface can not be used directly, and can not be immediately changed. The adapter can be converted to the interface we want to achieve code reuse.

Similar Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *