What is adapter mode?
Convert the interface of one class to another interface that the customer wants, so that classes that are not working together because they are incompatible can work together.
What scenario uses the adapter mode?
For example, we have to re-use some of the early code or third-party libraries or other maintenance of the code, but the interface of the code and we are not compatible with the environment at this time, we can not modify the code, so we need to use the adapter to adapt these interfaces for ease of use.
Use an existing class, but if its methods are different from yours, you should consider using adapter mode.
Note: The adapter pattern is not considered in the detailed design phase (development phase), which is to be considered for maintenance or extension of the existing functional system.
There are two main types of adapter modes:
Class Adapter mode and object adapter mode.
Class Adapter Mode:
Class adapters are created by inheriting the implementation class of the adapter interface and implementing the target interface. This allows the adapter to be used as an implementation class for the target interface and to invoke a method of the appropriate interface in the implementation class. So as to achieve the purpose of adaptation.
Example:
Target role
public interface target{
public void request ();
}
SOURCE role
public class adaptee{
The original business
public void dosomething () {
System.out.println ("a b C");
}
}
Adapter role
public class Adapter extends Adaptee implements target{
public void request () {
Super.dosomething ();
}
}
Object Adapter Mode:
By wrapping an adapted class object inside the adapter class, the source interface is converted to the target interface, where the class of the adapter is a subclass or implementation of the target class.
Example:
Target role
public interface target{
public void request ();
}
SOURCE role
public class adaptee{
The original business
public void dosomething () {
System.out.println ("a b C");
}
}
Adapter role
public class Adapter implements target{
Private Adaptee adaptee = new Adaptee ();
public void request () {
Adaptee.dosomething ();
}
}
The difference between an object adapter and a class adapter:
Class adapters are inter-class inheritance , but because Java does not allow multiple inheritance, we use object adapters when we need to adapt multiple classes, and object adapters are the composite relationships of objects or the association of Classes , which is the fundamental difference between the two.
Adapter Mode (Java Edition)