JavaScript design mode ITEM9--Adapter mode adapter

Source: Internet
Author: User

Adapter mode (Converter surface mode), generally for the interface to be used, does not conform to the application or the use of the system, and the need to introduce the intermediate adaptation layer class or object case. The role of adapter mode is to solve the problem of incompatible interface between the two software entities.

First, the definition

Adapter mode (Adapter) is the interface (method or property) that transforms a class (object) into another interface (method or property) that the customer wants, and the adapter mode makes it possible to work on those classes (objects) that would otherwise not work together because of incompatible interfaces. Crash Wrapper (wrapper).

The adapter alias is the wrapper (wrapper), which is a relatively simple pattern. There are many such scenarios in program development: When we try to invoke a module or an interface of an object, we find that the format of the interface does not match the current requirements. At this time there are two solutions, the first is to modify the original interface implementation, but if the original module is very complex, or we get the module is a piece of other people to write the compressed code, modify the original interface is not very realistic. The second option is to create an adapter that transforms the original interface into another interface that the customer wants, and the customer only needs to deal with the adapter.

Second, real-life adapter

Scene: Like we bought a cell phone, bought back found that the charging line plug is three plugs, but home, only two plug the mouth of the socket, how to do? For convenience, there is also to be able to charge in any place can be charged, you have to buy a universal charger adapter; So that the phone can be charged in their own home, or can only be placed, or run to the place where the plug is charged;

Three, adapter mode

If the existing interface is already working properly, then we will never use the adapter mode. Adapter mode is a "fix it" mode, no one will use it at the beginning of the design of the program. Because no one can fully anticipate the future, perhaps the interface that is working well now, the Future Day is no longer applicable to the new system, then we can use the adapter mode to wrap the old interface into a new interface, so that it continues to remain alive. For example, before the JSON format became popular, many CGI returned XML-formatted data, and if you still want to continue using these interfaces today, obviously we can create one.
the Xml-json adapter .

3.1 Parameter Adapter

Sometimes we need to pass n multiple arguments when defining a function, for example:

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

We have to remember that the order of these parameters is very difficult, how to do it? 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 invocation process, it is not known whether the parameters passed are complete, such as some of the necessary parameters are not passed in, some parameters have the initial value. At this point, you can use the adapter to adapt the requirements of these parameters, as follows:

function doSomething(params){    var _adapter={        name:"适配器",        title:"设计模式",        age:24,        color:"pink",        size:240,        prize:50};    for(var i in _adapter){        _adapter[i] = params[i] || _adapter[i];    }//或者extend(_adapter,params);这有可能会增加属性}
Four, data adapter

For example, in the development of some plug-ins, there are a lot of data adaptation, such as the following is an array
var arr=["JavaScript", "book", "front-end programming Weapon", "March 14";
We find that the data in the array represents a different meaning, which is semantically unfriendly, and we may require that it be translated into the form of an object:

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

As required, we can define such a data adapter

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

This gives us the flexibility to use the data to provide new ideas.

Five, front and rear data matching

When we send a "show" request to both GoogleMap and Baidumap, GoogleMap and Baidumap each show the map in their own way:

var googleMap = {    show: function(){        console.log( ‘开始渲染谷歌地图‘ );    }};var baiduMap = {    show: function(){        console.log( ‘开始渲染百度地图‘ );    }};var renderMap = function( map ){    if ( map.show instanceof Function ){        map.show();    }};renderMap( googleMap ); // 输出:开始渲染谷歌地图renderMap( baiduMap ); // 输出:开始渲染百度地图

The key to the smooth operation of this program is that GoogleMap and Baidumap provide a consistent show method, but the third-party interface method is not within our own control, if the BAIDUMAP provides a way to display the map is not called show and called Display it?

Baidumap This object comes from a third party, and under normal circumstances we should not change it. At this point we can solve the problem by adding Baidumapadapter:

var googleMap = {    show: function(){        console.log( ‘开始渲染谷歌地图‘ );    }};var baiduMap = {    display: function(){        console.log( ‘开始渲染百度地图‘ );    }};var baiduMapAdapter = {    show: function(){        return baiduMap.display();    }};renderMap( googleMap ); // 输出:开始渲染谷歌地图renderMap( baiduMapAdapter ); // 输出:开始渲染百度地图

Let's look at another example. Suppose we are writing a page that renders a map of Guangdong province. Currently, all cities in Guangdong province and their corresponding IDs are obtained from third-party resources and are 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( ‘开始渲染广东省地图‘ );    document.write( JSON.stringify( fn() ) );};render( getGuangdongCity );

Using this data, we have written the entire page and have been running stably on-line for some time. But later found that the data is not very reliable, there are many cities in the lack. So we found some other data resources on the Internet, this time the data is more comprehensive, but unfortunately, the data structure and is running in the project is not consistent. The new data structure is as follows:

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

In addition to the fact that the front-end code of the rendered page has been greatly rewritten, a more portable solution is to add an adapter with a 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 ) );

The next thing to do, then, is to call getguangdongcity in the code and replace it with a new function after the Addressadapter adapter is converted.

VI. Application Scenarios

What about using adapter mode properly? It is recommended to use the following scenarios if:

    • Use an already existing object, but its method or property interface does not meet your requirements;
    • You want to create a reusable object that can work with other unrelated objects or objects that are not visible (that is, interfaces that are incompatible with methods or properties);
    • You want to use an object that already exists, but you cannot prototype each one to match its interface. The object adapter can adapt its parent object interface method or property.

There are some patterns with the adapter mode
Structures are very similar, such as decorator mode , proxy mode , and appearance mode . These patterns are all part of the "package
The other object is wrapped by one object. The key to distinguishing them is still the intent of the pattern.

    • The adapter pattern is primarily used to address mismatches between two existing interfaces, regardless of how they are implemented or how they might evolve in the future. The adapter mode does not need to change an existing interface to make them work together.

    • Decorator mode and proxy mode do not change the interface of the original object, but the adorner mode is intended to add functionality to the object. The decorator pattern often forms a long decorative chain, while the adapter pattern is usually packaged only once. The proxy mode is to control access to objects and is usually wrapped only once.

    • The function of the appearance mode is similar to the adapter, some people regard the appearance pattern as the adapter of a set of objects, but the most notable feature of the appearance mode is the definition of a new interface.

JavaScript design mode ITEM9--Adapter mode adapter

Related Article

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.