First, what is the adapter
An adapter is a wrapper class that is transforming an interface into another interface;
Ii. Supplementary Notes
There are two ways of realization, one is through inheritance, the other by combination;
When using the combination implementation, the decorator pattern is a bit similar, but the focus is different, the decorator mode is to add new behavior to the object, adapter is to adapt the interface;
Advantages: In accordance with the open and closed principle, the adaptation of the class and target class decoupling; code reuse;
Third, the role
Target interface
Adapter class
Adapter class
User
Iv. examples, Java implementations
Introduction: Existing A USB interface and a PSP interface implementation class, the function is to charge, the purpose of this example is to the PSP interface implementation Class packaging, so that it can be charged with USB interface;
Target interface , charging with USB interface
Package Com.pichen.dp.structuralpattern;public interface Iusb {public void charge ();
A USB interface implementation class (this class does not belong to the role in adapter mode, just a contrast)
Package Com.pichen.dp.structuralpattern; Public class Implements iusb{ @Override publicvoid charge () { System.out.println (" Use HP USB interface to charge ~ ");} }
Adapter class , charging with PSP
Package Com.pichen.dp.structuralpattern; Public class PSP { publicvoid Pspcharge () { System.out.println ("Charge with PSP interface ~");} }
Adapter Class ( inherited ), Inherit PSP class, and implement Iusb interface
Package Com.pichen.dp.structuralpattern; Public class extends Implements iusb{ @Override publicvoid charge () { super . Pspcharge (); }}
Adapter classes (combined ), combining PSP objects, and implementing IUSB interfaces
Package Com.pichen.dp.structuralpattern; Public class Implements iusb{ private psp PSP; Public PSPAdapter2 (PSP PSP) { this. PSP= psp; } @Override publicvoid charge () { psp.pspcharge (); } }
User Main, test results
Package Com.pichen.dp.structuralpattern; Public class Main { publicstaticvoid main (string[] args) { new Hpusb (); Usb.charge (); New Pspadapter (); Usb_psp.charge (); New PSPAdapter2 (new PSP ()); Usb_psp2.charge (); }}
Printing results:
Charging using the HP USB interface ~ Charging using the PSP interface ~ charging using the PSP interface ~
Adapter Mode ★★★★☆