Objective: to convert an interface of a class into another interface that the customer wants. The A d a p t e r mode makes those classes that cannot work together due to interface incompatibility work together. Intent:
You want to use an existing class, and its interface does not meet your needs.
You want to create a reusable class that can work together with other unrelated classes or unforeseen classes (that is, classes whose interfaces may not be compatible.
(Only applicable to object a d a p t e r) You want to use existing subclasses, but it is impossible to subclass each of them to match their interfaces. The Object Adapter can adapt to its parent class interface. (The purpose and intent are unchanged. This is taken from the electronic version of the Design Pattern mini manual.) Below is an example of Java version I. Schematic diagram:
Ii. ExampleCode
/*** Created by intellij idea. * User: leizhimin * Date: 14:43:46 * Source role */public class adaptee {public int get220v () {return 220;} public int randromv () {return new random (). nextint (1000 );}}
/*** Created by intellij idea. * User: leizhimin * Date: 14:43:23 * Target role */public interface target {int get110v (); int get220v (); int getrandomv ();}
/*** Created by intellij idea. * User: leizhimin * Date: 14:43:07 * adapter role: extends the source role to implement the target role, so that the source role does not need to be changed when the target role is changed, change the adapter */public class adapter extends adaptee implements target {public int get110v () {return 110;} public int getrandomv () {return this. random ();}}
/*** Created by intellij idea. * User: leizhimin * Date: 15:00:31 * client */public class client {public static void main (string rags []) {new client (). test () ;}public void test () {Target target = new adapter (); int V1 = target. get110v (); int v2 = target. get220v (); int V3 = target. getrandom ();}}
The adapter extends the source role and implements the target interface to meet the 220 V and V voltage requirements. Use the random () method to match the getrandom () Interface Method in the interface, that is, the adapter mode.