Introduction to adapter patterns for Java design patterns

  • 2020-04-01 03:24:55
  • OfStack

This paper illustrates two adapter patterns, class adapter pattern and object adapter pattern, as follows:

1. Class adaptation mode:

For example, in earth's time, all mounts could only run but could not fly, and now many mounts can fly from earth. If, in earth's time, mounts could only run, and today's mounts can not only fly but also run, we can use a quasi-adaptation mode to achieve this.
The important thing to note here is that the adapter inherits the source class and implements the target interface.
The sample code is as follows:


package adapter;


public class Sources {

  public void run() {
    System.out.println("run");
  }

}

package adapter;


public interface ITarget {

  public void run();

  public void fly();
}

package adapter;


public class Adapter extends Sources implements ITarget {

  @Override
  public void fly() {
    System.out.println("fly");
  }

}

2. Object adaptation mode:

Suppose an adapter wants to adapt to more than one object. You can introduce these objects into the adapter and then invoke the methods of these objects.

The implementation code is as follows:


package adapter;


public class Animal {

  public void run() {
    System.out.println("run");
  }
}

package adapter;


public interface ITarget {

  public void run();

  public void fly();
}

package adapter;


public class Adapter implements ITarget {

  private Animal animal;

  //Private animal animal2... Multiple objects can be adapted

  public Adapter(Animal animal) {
    this.animal = animal;
  }

  
  public void fly() {
    System.out.println("fly");
  }

  
  public void run() {
    this.animal.run();
  }

}

Related articles: