Java's Adapter Pattern

  The so-called adapter mode is actually very simple, which is to convert the interface of one class into another interface expected by the client, so that the two originally incompatible classes can work together.

  Suppose we have a Type-c interface, but the interface to be used is indeed a usb interface. What should we do at this time? The solution is to use an adapter to convert the Type-c class to the usb class, so that we can use the Type-c interface.

  There are two ways to implement the adapter pattern, namely composition and inheritance.

  1. Combination

  The combination method is to combine the adapted objects into the adapter class, where the adapted object is the Type-c interface.

  2. Inheritance

  Inheritance is through multiple inheritance of incompatible interfaces to match the target interface.

  The implementation code is as follows:

Usb.java
 package com.muggle.Ada;

public class Usb {
    public void useUsb() {
        System.out.println( "Usb interface is used" );
    }
}


Typec.java
package com.muggle.There;

public interface Tyepec {
    public void useTypec() ;
}


Adapter.java
package com.muggle.Ada;
 // Use the combination to implement the adapter mode 
public  class Adapter implements Tyepec {
     private Usb plug;

    public   Adapter(Usb plug) {
        // TODO Auto-generated constructor stub
        this.plug=plug;
    }
                                                                                                                                                                                                                                                   
    @Override
    public void useTypec() {
        // TODO Auto-generated method stub
        plug.useUsb();
        System.out.println( "The type-c interface is used to complete the conversion" );
        
    }

}

newAdapter.java
package com.muggle.There;

public  class newAdapter extends Usb implements Tyepec {
   // Use inheritance to implement adapter mode   
    @Override
     public  void useTypec() {
         // TODO Auto-generated method stub 
        this .useUsb();
        System.out.println( "The type-c interface is used to complete the conversion" );
    }

}

TestDrive.java
package com.muggle.There;


public class TestDrive {

    public static void main(String[] args) {
        Tyepec tyepec=new Adapter(new Usb());
        tyepec.useTypec();
        
        Tyepec newtypec=new newAdapter();
        newtypec.useTypec();
    }

}

  The results are as follows:

Use the usb interface
to complete the conversion Use the Type-c interface to complete the conversion Use
the usb interface
to complete the conversion Use the Type-c interface

  In this way, we have used the two methods of the adapter mode to convert the usb class.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324688017&siteId=291194637