Key points:
1. the adapter mode is mainly used in scenarios where you want to reuse some existing classes, but the interfaces are inconsistent with the requirements of the reuse environment. It is useful in legacy code reuse and class library migration.
2. the adapter mode has two forms of implementation structure: Object Adapter and class Adapter. However, the class adapter adopts the "Multi-inheritance" implementation method, resulting in poor high coupling. Therefore, it is generally not recommended. The Object Adapter adopts the "Object combination" method, which is more compliant with the loose coupling spirit.
Implementation:
Class adapter pattern structure (inherited)
Object Adapter pattern structure (combination)
(Object Adapter code implementation)
Target: defines the interfaces used by the Client in specific fields.
public interface Target { void request();}
Adaptee: The existing interface to be adapted
public class Adaptee{ public void specificRequest(){}}
Adapter: Adapt the Adaptee interface to the Target interface.
public class Adapter implements Target{ public Adapter(Adaptee adaptee) { super(); this.adaptee = adaptee; } public void request() { adaptee.specificRequest(); } private Adaptee adaptee;}
Applicability:
1. The system needs to use an existing class, and such an interface does not meet the requirements of the system.
2. Create a reusable class for some classes that are not highly correlated with each other, including some classes that may be introduced in the future. These source classes do not necessarily have very complex interfaces.
3. (For object adapters) in the design, you need to change the interfaces of multiple existing sub-classes. If you use the class adapter mode, you need to create an adapter for each sub-class, which is not practical.
Effects and advantages and disadvantages:
For Class adapters:
1. Use a specific Adapter class to match Adaptee and Taget. The result is that when we want to match a class and all its subclasses, the class Adapter will not be competent.
2. Make the Adapter override (redefinition) partial behavior of Adaptee, because the Adapter is a subclass of Adaptee.
For object adapters:
1. Allow an Adapter to work with multiple Adaptee, that is, the Adaptee itself and all its subclasses (if any. The Adapter can also add functions to all Adaptee at a time.
2. Making override (redefinition) Adaptee behavior more difficult. If you need the override Adaptee method, you have to first create an Adaptee subclass using the override Adaptee method, and then use this subclass as a real Adaptee source for adaptation.