Definition: The adapter pattern transforms the interface of a class into another interface that the customer expects. Those classes that would otherwise not work together because of incompatible interfaces can work together.
(For example: a computer needs an item socket, 220V power, now has three sockets and 110V power supply, how to make it work, now need socket adapter and power adapter)
The "ligand" is combined as an object into the adapter class, and a modification of the target interface wrapper is made to the appropriate person.
Adapter classification
1 combination
Adapter with combination as an object adapter
Feature: Combine the "ligand" as an object into the adapter class, a modification to the target interface wrapper by the appropriate person
2 inheritance
A class adapter that uses inheritance
Features: Through multiple inheritance incompatible interfaces, to achieve the matching of the target interface, a single for a class to achieve a suitable
Package Com.immoc.pattern.adapter;public class Gbtwoplug {public void Powerwithtwo () {System.out.println ("using two-phase power Source "); }}
Package com.immoc.pattern.adapter;/** * Three item Socket Connector */public interface Threeplugif {//use three current supply public void Powerwiththre E ();}
package com.immoc.pattern.adapter;/** * Two phase to three-phase socket adapter (using combination) */public class twoplugadapter implements threeplugif { private gbtwoplug plug; public twoplugadapter ( Gbtwoplug plug) { this.plug = plug; } public void powerwiththree () { system.out.println ("by conversion"); Plug.powerwithtwo (); }}
package com.immoc.pattern.adapter;/** * In the way of inheritance */public class twoplugadapterextends extends gbtwoplug implements threeplugif { public void powerwiththree () { system.out.println ("with Inheritance adapter"); this.powerwithtwo (); }}
Package com.immoc.pattern.adapter;public class notebook { private threeplugif plug; public notebook (ThreePlugIf plug) { this.plug = plug; } //using a socket to charge public void charge () { plug.powerwiththree (); } public Static void main (String[] args) { gbtwoplug two = new gbtwoplug (); threeplugif Three = new twoplugadapter (; notebook ) Nb = new notebook (three); nb.charge (); &nbSp; three = new twoplugadapterextends (); nb = new notebook (three); nb.charge (); }}
Characteristics:
1 Transparent
Through the adapter, the client can call the same interface, so it is transparent to the client, so that the seat is simpler, more direct, more compact.
2 Reuse
The existing classes are reused, which solves the problem that the existing classes and reuse environments require inconsistent requirements.
3 Low coupling
Decoupling the target class from the adapter class by introducing a suitable class to reuse the existing adaptation class without modifying the original code (to close the switch and open the extension)
Design mode-Adapter mode