An overview of the
The purpose of the adapter pattern is to resolve interface incompatibilities between two objects. Using the adapter pattern, two objects that would otherwise not work due to incompatible interfaces can work together.
Take an example in life: Hong Kong type plug converter, Hong Kong type electrical plug than the mainland electrical plug volume is larger. If we bought a Mac Book from Hong Kong, we would find that the charger wouldn’t fit into the socket at home, so it would be inconvenient to remodel the socket at home, so we needed a plug to switch.
using
From the example above, we can see that the adapter pattern has three roles:
- Target: Mainland electrical plug
- Adaptee: Hong Kong-style electrical plug
- Adapter role: The hong Kong-style electrical plug into the smaller mainland electrical plug, to match the mainland socket
Target role realization
class Target {
small(){
throw new Error('This method must be overwritten! '); }}Copy the code
With the Target interface to fulfill the Target role, users expect smaller electrical plugs.
Source role implementation
class Adaptee {
big(){
console.log("Hong Kong-style electrical plug available ~~"); }}Copy the code
Adaptee belongs to the larger Hong Kong-style electrical plug, which is different from what users have come to expect. So an adapter needs to be introduced to translate into the desired target interface.
Adapter implementation
class Adapter extends Target {
constructor(adaptee) {
super(a);this.adaptee = adaptee;
}
small() {
this.adaptee.big(); }}Copy the code
Adapter class inherits Target, overwrites small function, and finally transforms Hong Kong big into mainland small through Adapter.
Test the
let adaptee=new Adaptee(); let adapter=new Adapter(adaptee); adapter.small(); Hong Kong-style electrical plug available ~~Copy the code