Common Java design patterns-adapter patterns
The Adapter mode is introduced to solve the incompatibility mismatch problem.
Definition:
The adapter mode converts the excuse of a class into another interface that the customer expects, so that the classes that originally cannot work together due to interface incompatibility can work together.
Category:
1. Combination Method-Object Adapter
Feature: the adapter is combined into the adapter as an object to modify the Target Interface and encapsulate the adapter.
2. inheritance-class adaptation thick ky "http://www.bkjia.com/kf/ware/vc/" target = "_ blank" class = "keylink"> vc8L3A + kernel/seq907/kernel + c1_vcd4kpha + PHN0cm9uZz7A/kernel/WPC9zdHJvbmc + kernel/kernel + CjxwPjxwcmUgY2xhc3M9 "brush: java; "> public interface ThreePlugIf {public void powerWithThree ();}
2) define a class of sockets for the second item of the National Standard
Public class GBTwoPlug {public void powerWithTwo () {System. out. println ("using two current supplies ");}}
3) The socket adapter inherits ThreePlugIf
Import offers. threePlugIf;/** two to three outlet adapters */public class TwoPlugAdapter implements ThreePlugIf {private GBTwoPlug plug; public TwoPlugAdapter (GBTwoPlug plug) {this. plug = plug ;}@ Overridepublic void powerWithThree () {System. out. println ("converted"); plug. powerWithTwo (); // note that two power supplies are investigated in three power supply methods }}
4) define the notebook class for verification
public class NoteBook {private ThreePlugIf plug;public NoteBook(ThreePlugIf plug){this.plug = plug;} public void charge(){plug.powerWithThree();}public static void main(String[] args) {GBTwoPlug two = new GBTwoPlug();ThreePlugIf three = new TwoPlugAdapter(two);NoteBook nb = new NoteBook(three);nb.charge();}}
Conclusion: Functions of the adapter Mode
1. Transparent
Through the adapter, the client can call the same interface, so it is transparent to the client, which is simple, direct, and compact.
2. Reuse
The existing classes are reused to solve the inconsistency between the existing classes and the reuse environment.
3. Low Coupling
Decouples the target class and adapt, and the adapter class reuses the new adapter class without modifying the code (Open and Close principles ).