“This is the fifth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

Definition: To convert an interface of a class to require another interface. Enables classes to be used together that would not otherwise work together. In plain English, it converts one interface into another and interface.

Most of our current mobile phones have cancelled the headphone jack. When we need to use wired earphones, we cannot directly connect to the mobile phone, but need a Type-C to 3.5mm interface to connect to the mobile phone, which is what we call an adapter.

1. First we have an earphone

 public class Earphone{
     
     public void listen(a){
         system.out.println("I'm a headset: I need a 3.5mm jack to listen to music."); }}Copy the code

2. Earphones rely on a 3.5mm port

 public interface Three{
     public void provideThree(a);
 }
Copy the code

3. The type-c port is connected to the mobile phone

 public class TypeC{
     public void provideTypeC{
         System.out.println("I'm the TypeC interface for my phone."); }}Copy the code

4. Here are the adapters that connect your phone to your headphones

 public class Transfer implements Three{
     TypeC typeC;
     
     public Transfer (TypeC typeC){
         this.typeC = typeC;
     }
     
     @Override
     public void provideThree(a)
     {
         // After various operations -->3.5mm
         System.out.println("I am an adapter that can convert Type-C to 3.5mm."); }}Copy the code

5. Finally, we use earphones to listen to songs

 public class Test
 {
     public static void main(String[] args)
     {
         Earphone earphone = new Earphone();
         Three three = new Transfer(newTypeC()) ; earphone.listen(three); }}Copy the code

Output:

I am the type-C port of the mobile phone. I am the adapter that can convert the Type-C port to 3.5mm. I am the earphone: I need the 3.5mm port to listen to musicCopy the code

It can be seen that a conversion interface is used to complete the task of converting type-C interface into 3.5mm interface, and the headset and Type-C interface are completely decoupled.

So when do we use it? It is used when the system needs to use an existing class but does not have an interface that meets its needs

Advantages: 1. Can make any two unrelated classes run together. 2, can improve the reuse of classes. 3. Excellent flexibility.

Disadvantages: 1, too much use of adapters, will make the system very messy, not easy to grasp the whole. So if you don’t specifically need an adapter, it’s best to refactor the code directly. After all, a phone without a headphone jack doesn’t come cheap.