The adapter pattern converts one interface into another to achieve compatibility with several interfaces. For example, a computer has a USB port, but if you want to transfer data to a memory card, you need a card reader. In this case, the card reader acts as an adapter to convert the USB port into a memory card port, which is compatible with the memory card. In the program design will also encounter the problem of incompatible interface, you need something similar to the card reader to do interface adaptation.

Here is the code to implement the adapter pattern:

Now you have an interface, and it has a run method, and the Dog class implements that interface, and it can run with the run method.

public interface Target {
    void run(a);
}
public class Dog implements Target {
    @Override
    public void run(a) {
        System.out.println("The dog is running"); }}Copy the code

Now there is a car, the car can only run through the drive method.

public class Car {
    public void drive(a){
        System.out.println("The car was driven"); }}Copy the code

We just want everything to run with the run method, and we need to adapt Car.

There are two adapter modes.

The first is class adaptation via inheritance:

public class AdapterByClass extends Car implements Target{
    @Override
    public void run(a) {
        super.drive(); }}Copy the code

The second is object adaptation through object composition:

public class AdapterByObject implements Target{ private Car car; public AdapterByObject(Car car) { this.car = car; } @Override public void run() { car.drive(); }}Copy the code

User use:

public class Main { public static void main(String[] args) { Target target1 = new Dog(); target1.run(); Target target2 = new AdapterByClass(); target2.run(); Target target3 = new AdapterByObject(new Car()); target3.run(); }}Copy the code

The running result is shown as follows:

As you can see, just by using the run method, both car and dog can run, and the car adaptation is successful.

Adapter mode benefits:

  1. Masking some of the underlying differences, callers use simple, straightforward, and do not care about the underlying call relationship.
  2. By introducing an adapter class, the interface calls can be unified without modifying the code of the adaptor.
  3. Increased code reuse

Adapter pattern disadvantages:

  1. The use of adapter mode indicates that the original architecture has shortcomings, usually have similar functions but the interface is different to make adapter adaptation, which indicates that the original different interface can be abstracted from the more basic interface. So the adapter is a defect remedy measure.
  2. The adapter pattern increases the depth of the call stack, which increases system complexity. From the outside, interface A is called, and the result is that the inside is adapted to call interface B, making the call more complicated.