Java implements Adapter pattern

The Adapter pattern belongs to the structural design pattern. It converts the interface of a class into another interface expected by the client, so that two classes that could not work together because of interface mismatch can work together. The Adapter pattern can solve the compatibility problem of the system, so that the incompatible interfaces can work together seamlessly. Applicable scenario: 1. When the system needs to use existing classes, and the interfaces of these classes do not meet the requirements of the system, the Adapter pattern can be used. 2. When you need to reuse some existing classes, but the interfaces of these classes do not meet the current system requirements, you can use the Adapter pattern. 3. When you need to create a reusable class that works with some incompatible classes, you can use the Adapter pattern. The Adapter pattern has three main roles: 1. Target interface: Define the interface that the client expects to use. 2. Adapter: The adapter implements the target interface, which contains an adapted object. 3. Adaptee: An existing class or object that needs to be adapted. The following is the sample code of a Java Adapter pattern: //Target interface interface Target { void request(); } //Adapted class Adaptee { public void specificRequest() { System. out. println ("The method of the adapter is called"); } } //Adapter class Adapter implements Target { private Adaptee adaptee; public Adapter(Adaptee adaptee) { this.adaptee = adaptee; } public void request() { adaptee.specificRequest(); } } //Client public class Client { public static void main(String[] args) { Adaptee adaptee = new Adaptee(); Target target = new Adapter(adaptee); target.request(); } } In the above code, 'Target' is the interface that the client expects to use, 'Adaptee' is an existing adapted class, and 'Adapter' is an adapter that implements the 'Target' interface and includes an 'Adaptee' object. In the client code, first create a 'Adaptee' object, and then convert it into an object available to the target interface 'Target' through the adapter 'Adapter', and call the 'request()' method. The execution result is printed as' the method of the adapted person has been called '.