Adapter is to transform the interface of one class into another interface expected by the customer, so that the classes that are not compatible with the original interface can work together.

In adapter: define a wrapper class, incompatible interface object, wrapper class is adapter, wrapper object is adapter

Configurator mode has four roles:

Target: target abstract class

Adapter: adapter class

Adapter: adapter class

Client: customer class

/*
 * Define a method to be implemented after an interface definition
 * */
public interface Robot {

	//Define two call and move methods
	void cry();
	void move();
}
/*
 * Define an entity class Cat
 * */
public class Cat {
	public void miao() {
		System.out.println("Meow, meow...");
	}
	public void run() {
		System.out.println("Four claws running");
	}

}
/*
 * Defining a class to imitate robot to realize robot
 * */
public class BioRobot implements Robot {

	@Override
	public void cry() {
		System.out.println("Generate a robot that can be called!");
		
	}

	@Override
	public void move() {
		System.out.println("Generate a mobile robot!");
		
	}

}
/*
 * Adapter class, robot mimics cat
 * */
public class CatAdapter implements Robot {

	Cat cat;
	public CatAdapter(Cat cat) {
		//References to objects to fit
		this.cat = cat;
	}
	/*
	 * To implement the methods in the interface, only the transformation between the corresponding methods is needed.
	 * */
	@Override
	public void cry() {
		System.out.println("Robot mimics cat call");
		cat.miao();
		
	}

	@Override
	public void move() {
		System.out.println("Robot imitates walking");
		cat.run();
	}

}
/*
 * Client
 * */
public class Client {

	public static void main(String[] args) {
		//We need a robot, so we need a new one first.	
		
		BioRobot robot = new BioRobot();
		//You also need an object to imitate
		Cat cat = new Cat();
		
		//Packaging imitated entities into robots
		Robot catRobot = new CatAdapter(cat);
		
		//Robot behavior
		System.out.println("These behaviors of robots:");
		catRobot.cry();
		catRobot.move();
	}
}

Advantage:

  1. The target class and the adapter class are decoupled, the incompatible interface is made compatible by using the adapter, and the customer is decoupled from the implemented interface.
  2. It increases the transparency and reusability of the class, encapsulates the specific implementation in the adapter class, which is transparent for the client class and improves the reusability of the adapter.
  3. Flexibility and extensibility, adding new adapter classes without modifying the original code

 

Usage scenario:

  • The system needs to use existing classes whose interfaces do not meet the needs of the system
  • I want to build a reusable class for some classes that are not very related to each other.