The adapter pattern is to transform the interface of one class into another interface that the client expects, so that two classes that would otherwise not work together because of an interface mismatch can work together.
An example of an adapter pattern:
Please do a specific class of kittie and implement methods such as Miao (), Catchrat (), run (), sleep (), and so on. To do a puppie interface, requires WAO (), Fetchball (), run (), sleep () and other methods. Now John has a friend who wants a pupple, but finds only one kittie. John needs to use the adapter mode to "fit" the Kittie into a puppie to make his friends happy. Ask John what to do (hint: do what you Can).
The hint can be possibilities, so John needs to fit Miao () to Wao (), Catchrat () to Fetchball (), run (), and sleep () remains the same. The system source code is as follows:
The system needs a class with a Puppie interface, and here is the source code for the Puppie interface that plays the target role.
/* * Puppie interface for target role * */public interface Puppie {public void Wao ();p ublic void Fetchball ();p ublic void Run ();p ublic void SL EEP ();p ublic void SetName (string name);p ublic string GetName ();
Next is the source code for the Kittie class that plays the source role of the adapter pattern. The Kittie class is a class that is similar to the existing function of the system, but its interface is different from that of the puppie and therefore does not meet the requirements.
/* * Kittie Source code * */public class Kittie {private String name;public void Miao () {}public void Catchrat () {}public void run () { }public void Sleep () {}public String getName () {return name;} public void SetName (String name) {this.name = name;}}
The following is the core role adapter role of the adapter pattern, which is played by the John Class
public class John extends Kittie implements puppie{@Overridepublic void Wao () {//TODO auto-generated method Stubthis.miao ();} @Overridepublic void Fetchball () {//TODO auto-generated method Stubthis.catchrat ();} public void Run () {Super.run ();} public void Sleep () {super.sleep ();} public void SetName (String name) {super.setname (name);} Public String GetName () {return super.getname ();}}
When do you use adapter mode?
The system needs to use the existing classes, and the interfaces of this class do not meet the needs of the system.
Adapter Mode (Adapter)