Adapter (adapter mode)
In real life, there are often instances where two objects cannot work together due to incompatible interfaces. At this time, a third party needs to adapt. For example, a Chinese speaker needs an interpreter when talking to an English speaker, a power adapter when using a DC laptop to connect to an AC power supply, a card reader when using a computer to access the SD memory card of the camera, etc.
Definition and characteristics of pattern
The definition of adapter pattern is as follows: convert the interface of a class into another interface desired by the customer, so that those classes that cannot work together due to interface incompatibility can work together. Adapter patterns are divided into class structured patterns and object structured patterns. The former has a higher degree of coupling between classes than the latter, and requires programmers to understand the internal structure of relevant components in the existing component library, so there are relatively few applications.
Structure and implementation of pattern
- Target interface: the interface expected by the current system business. It can be an abstract class or interface.
- Adapter class: it is the component interface in the existing component library accessed and adapted.
- Adapter class: it is a converter that converts the adapter interface into the target interface by inheriting or referencing the adapter object, so that customers can access the adapter according to the format of the target interface.
package adapter; //Target interface interface Target { public void request(); } //Adapter interface class Adaptee { public void specificRequest() { System.out.println("The business code in the adapter is called!"); } } //Class adapter class class ClassAdapter extends Adaptee implements Target { public void request() { specificRequest(); } } //Client code public class ClassAdapterTest { public static void main(String[] args) { System.out.println("Adapter class test mode:"); Target target = new ClassAdapter(); target.request(); } }
Class adapter mode test:
The business code in the adapter is called!
In the object adapter mode, the adapter does not inherit the adaptee Adaptee to modify incompatible content, but uses the adapter object as an attribute in the class, and the overall method remains unchanged.
Structure diagram of object adapter pattern
package adapter; //Object adapter class class ObjectAdapter implements Target { private Adaptee adaptee; public ObjectAdapter(Adaptee adaptee) { this.adaptee=adaptee; } public void request() { adaptee.specificRequest(); } } //Client code public class ObjectAdapterTest { public static void main(String[] args) { System.out.println("Object adapter mode test:"); Adaptee adaptee = new Adaptee(); Target target = new ObjectAdapter(adaptee); target.request(); } }