Overview
Converting an interface to another interface the user desires, Adapter mode allows classes that could not work together because of incompatibility of the interfaces.
Two implementation methods
1. Class adapter mode:
2. Object adapter mode:
The UML diagram of the adapter mode of the class is as follows:
The class's adapter pattern converts the adapted class's API into the target class's API.
The characters designed in the picture above are:
Target: This is the interface you are looking for.
Source Role (Adapee): The interface that is now needed to adapt.
Adapter role (Adapter): It is the core of this mode, and the adapter converts the source interface into the target interface.
Code example:
interface Target{ void method1(); void method2(); //I hope to get this method}//The source class does not have the method in method2. class Adaptee{ public void method1(){ System.out.println("method1"); }}class Adapter extends Adaptee implements Target{ @Override public void method2() { System.out.println("this is target method"); }}public class MainTest { public static void main(String arg[]) { Target target = new Adapter(); target.method2(); }} The UMl diagram of the object's adapter mode is as follows:
The core idea is the same as the adapter mode of the class. It only changes the Adapter class, does not inherit the Adaptee class, but holds a reference to the Adaptee class. The code is as follows:
interface Target{ void method1(); void method2();}class Adaptee{ public void method1(){ System.out.println("method1"); }}class Adapter implements Target{ private Adaptee adaptee; public Adapter(Adaptee adaptee){ this.adaptee = adaptee; } @Override public void method2() { System.out.println("this is target method"); } @Override public void method1() { // TODO Auto-generated method stub adaptee.method1(); }}public class MainTest { public static void main(String arg[]) { Target target = new Adapter(new Adaptee()); target.method2(); }} Advantages and disadvantages of adapter mode:
Better reusability and better scalability. The system needs to use existing classes, and such interfaces do not meet the needs of the system, so these functions can be better reused through the adapter mode. When implementing the adapter function, you can call the functions you developed by yourself to naturally expand the functions of the system.
Disadvantages: Too much use of adapters will make the system very messy and difficult to grasp overall.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.