JavaScript Design Pattern Item9 -- Adapter pattern Adapter

Source: Internet
Author: User

JavaScript Design Pattern Item9 -- Adapter pattern Adapter

Adapter mode (converter surface mode) is generally used for the interface, does not match the application or the system, and the intermediate Adaptation Layer class or object needs to be introduced. The adapter mode is used to solve the problem of interface incompatibility between two software entities.

I. Definition

The Adapter mode converts an interface (method or attribute) of a class (object) to another interface (method or attribute) that the customer wants ), the adapter mode makes it possible for classes (objects) that cannot work together due to interface incompatibility. Wrapper ).

The alias of the adapter is wrapper, which is a relatively simple mode. There are many scenarios in program development: when we try to call an interface of a module or object, we find that the Interface format does not meet the current requirements. There are two solutions at this time. The first one is to modify the original interface implementation, but if the original module is very complicated, or the module we get is a piece of compressed code compiled by others, it is unrealistic to modify the original interface. The second method is to create an adapter and convert the original interface to another interface that the customer wants. The customer only needs to deal with the adapter.

2. Real-Life adapters

Scenario: We bought a mobile phone. After buying it, we found that the charging wire plug is a three-plug, but there are only two plug-in sockets in the house. What should we do? For convenience, you have to buy a universal charging adapter to enable power-on anywhere. In this way, you can only power-on your phone at home. Otherwise, you can only put it on, or run to a place with this plug to charge;

Iii. Adapter Mode

If the existing interface is working properly, we will never use the adapter mode. The adapter mode is a "desperate" mode, and no one will use it at the beginning of the design of the program. Because no one can fully predict what will happen in the future, maybe the interfaces that work well now will no longer apply to new systems in the future, then we can use the adapter mode to wrap the old interface into a new interface to keep it alive. For example, before the popular JSON format, many cgi returns XML data. If you still want to use these interfaces today, we can create one.
XML-JSON Adapter.

3.1 parameter Adapter

Sometimes, when defining a function, we need to pass N multiple parameters, for example:

function doSomething(name,title, age,color,size,prize){}

It is difficult to remember the order of these parameters. What should we do? We often pass in the form of a parameter object, as follows:

/* params.name:name   params.title:title   params.age:age   params.color:color   params.size:size   params.prize:prize*/function doSomething(params){}

However, in the actual call process, you do not know whether the passed parameters are complete. For example, some required parameters are not passed in, and some parameters have initial values. In this case, you can use the adapter to adapt to the requirements of these parameters, as follows:

Function doSomething (params) {var _ adapter = {name: "adapter", title: "design mode", age: 24, color: "pink", size: 240, prize: 50}; for (var I in _ adapter) {_ adapter [I] = params [I] | _ adapter [I];} // or extend (_ adapter, params); this may add attributes}
Iv. data adapter

For example, in the development of some plug-ins, there are a lot of data adaptation, for example, the following is an array
Var arr = ["javascript", "book", "front-end programming tool", "March 14"];
We found that the data in the array represents different meanings. This data is not semantically friendly and we may ask to convert it into an object:

var obj={    name:"",    type:"",    title:"",    time:""}

We can define such a data adapter as needed

function arrToObjAdapter(){  return{    name:arr[0],    type:arr[1],    title:arr[2],    date:arr[3]  };}var adapterData = arrToObjAdapter(arr);console.log(adapterData);

This provides us with new ideas for flexible use of data.

V. frontend and backend data adaptation

When we send a "display" request to both googleMap and baiduMap, googleMap and baiduMap display the map in their respective ways on the page:

Var googleMap = {show: function () {console. log ('start rendering Google map') ;}}; var baiduMap = {show: function () {console. log ('start rendering Baidu map') ;}; var renderMap = function (map) {if (map. show instanceof Function) {map. show () ;}}; renderMap (googleMap); // output: Start to render Google map renderMap (baiduMap); // output: Start to render Baidu Map

The key to the smooth operation of this program is that googleMap and baiduMap provide the same show method, but the third-party interface method is not within our control scope, what if the map display method provided by baiduMap is not "show" but "display?

The baiduMap object comes from a third party. Normally, we should not change it. Now we can solve the problem by adding the baiduMapAdapter:

Var googleMap = {show: function () {console. log ('start rendering Google map') ;}}; var baiduMap = {display: function () {console. log ('start rendering Baidu map') ;}; var baiduMapAdapter ={ show: function () {return baiduMap. display () ;}}; renderMap (googleMap); // output: Start to render Google map renderMap (baiduMapAdapter); // output: Start to render Baidu Map

Let's take a look at another example. Suppose we are writing a page for rendering the map of Guangdong. Currently, all cities in Guangdong Province and their corresponding IDs are obtained from third-party resources and successfully rendered to the page:

Var getGuangdongCity = function () {var guangdongCity = [{name: 'shenzhen', id: 11, },{ name: 'guangzhou ', id: 12,}]; return guangdongCity;}; var render = function (fn) {console. log ('start rendering Guangdong map '); document. write (JSON. stringify (fn ();}; render (getGuangdongCity );

With this data, we have compiled the entire page and ran stably online for a period of time. However, it was found that the data was not reliable and many cities were missing. So we found some other data resources on the Internet. This time, the data is more comprehensive, but unfortunately, the data structure is inconsistent with that in the project. The new data structure is as follows:

var guangdongCity = {    shenzhen: 11,    guangzhou: 12,    zhuhai: 13};

In addition to rewriting the front-end code of the rendering page, a more lightweight solution is to add an adapter for data format conversion:

var addressAdapter = function( oldAddressfn ){   var address = guangdongCity,   oldAddress = oldAddressfn();   for ( var i = 0, c; c = oldAddress[ i++ ]; ){        address[ c.name ] = c.id;   }   return address;};render( addressAdapter( getGuangdongCity ) );

Next, we need to call the getGuangdongCity function in the Code and use the new function after the addressAdapter adapter conversion.

Vi. application scenarios

Is the adapter mode suitable? If the following conditions occur, we recommend that you:

Use an existing object, but its method or attribute interface does not meet your requirements. you want to create a reusable object, this object can work with other irrelevant objects or invisible objects (that is, objects with incompatible interface methods or attributes). To use an existing object, however, you cannot perform prototype inheritance on each interface to match it. The Object Adapter can adapt to its parent object interface methods or attributes.

There are some modes and adapter Modes
The structure is very similar, suchDecoration Mode,Proxy ModeAndAppearance Mode. These modes all belong to the "package
The installation mode "is to wrap another object by one object. The key to distinguishing them is the intention of the pattern.

The adapter mode is mainly used to solve the mismatch between two existing interfaces. It does not consider how these interfaces are implemented or how they may evolve in the future. In the adapter mode, you do not need to change existing interfaces to make them work together.

The decorator mode and proxy mode do not change the interface of the original object, but the decorator mode is used to add functions to the object. A long decorative chain is often formed in the modifier mode, while the adapter mode is usually packed only once. The proxy mode is used to control access to objects. It is usually encapsulated only once.

The appearance mode is similar to the adapter. Some people regard the appearance mode as a set of object adapters, but the most significant feature of the appearance mode is to define a new interface.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.