Adapter mode description
Description: Adapter mode is generally used when the interface to be used is not suitable for this application or system, and an intermediate adaptation layer class or object needs to be introduced;
Scenario: It’s like we bought a mobile phone. After we bought it, we found that the charging cord has a three-prong plug, but there are only two-prong sockets at home. What should we do? For convenience and to be able to charge it anywhere, you have to buy a universal charging adapter so that your phone can be charged at home. Otherwise, you can only leave it alone or go to a place with a plug to charge it.
In the actual development environment, because the interfaces provided by the old system or third-party applications do not match the interfaces we define, such old or third-party interfaces cannot be used in an interface-oriented programming environment. , then we use the adaptation class to inherit the class to be adapted, and let the adaptation class implement the interface to introduce the interface of the old system or third-party application;
When using interface programming in this way, you can use this adaptation class to indirectly call the interface of the old system or third-party application.
In Javascript, if you want to implement code similar to the adapter pattern of a dynamic object-oriented language, you can use the inherited instance of prototype to implement it; because it is based on interface constraints, but Javascript does not have such a thing as an interface, we remove the interface layer. Directly implement the interface implementation class Target and simulate similar source code;
Source code example
1. Classes and interface methods to be adapted:
2. Ordinary implementation class [Since there is no interface in Javascript, the implementation class is provided directly]
Target.prototype.queryName= function() {
Return this.name;
}
3. Adaptation class:
Adapte.prototype = new Adaptee();
Adapte.prototype.queryName = function() {
This.getName();
}
4. How to use:
var adapte = new Adapte();
adapt.queryName(); //Call the old system or third-party application interface;
Other instructions
In the fourth step above, var local and var adapt are similar to the interface reference designation in object-oriented languages such as Java and C#, such as:
//Adapter
Target adapte = new Adapte();
adapt.queryName();
It can be seen that the adapter class is the middle layer that connects the interface and the target class interface; it is used to solve the problem that the required target already exists, but we cannot use it directly or in conjunction with our code definition, so we have to use the adapter mode , adapter mode is also called conversion mode and packaging mode;