JavaScript design mode-Adapter mode

Source: Internet
Author: User

Previous words

The role of adapter mode is to solve the problem of incompatible interface between the two software entities. After using adapter mode, two software entities that were originally unable to work because of incompatible interfaces could work together. The adapter alias is the wrapper (wrapper), which is a relatively simple pattern. There are many such scenarios in program development: When attempting to invoke an interface of a module or an object, it is found that the format of the interface does not meet 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 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. This article describes the adapter mode in detail

Adapters in the real world

Adapters are widely used in real life, and next look at several real-life adapter patterns

1, Hong Kong-style plug converter

Hong KONG-style electrical plugs larger than the mainland's electrical plug volume. If you buy a MacBook from Hong Kong, you will find that the charger is not plugged into the home outlet, so it is not convenient to retrofit the home outlet, so you need an adapter:

2. Power adapter

The MacBook Battery supports a voltage of 20V, and the AC voltage in daily life is generally 220V. In addition to understanding the 220V AC voltage, the AC voltages in Japan and Korea are mostly 100V, while the UK and Australia are 240V. The power adapter of the laptop is responsible for the conversion voltage, and the power adapter makes the laptop work within the 100v~240v voltage, which is why it is called the power adapter.

3, USB interface

On previous computers, the PS2 interface was the standard interface for connecting the mouse, keyboard, and other external devices. But with the development of technology, more and more computers began to abandon the PS2 interface, and instead only supported the USB interface. So those who produced in the past only have PS2 interface mouse, keyboard, gamepad, etc., need a USB interface to continue to work properly, this is the reason why the Ps2-usb adapter was born

Application

If the existing interface is already working properly, it will never be used in 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 of things, perhaps now good work of the interface, one day in the future is no longer applicable to the new system, then you can use the adapter mode to wrap the old interface into a new interface, so that it continues to maintain vitality. 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, you can obviously create an Xml-json adapter

Here is an example where GoogleMap and Baidumap show the map in their own way when the "show" request is made to both GoogleMap and Baidumap:

varGoogleMap ={show:function () {Console.log ('Start rendering Google Maps' ); }};varBaidumap ={show:function () {Console.log ('Start rendering Baidu map' ); }};varRendermap =function (map) {if(map.show instanceof Function) {map.show (); }};rendermap (GOOGLEMAP); //output: Start rendering Google MapsRendermap (BAIDUMAP);//output: Start rendering Baidu map

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 the control range, if the Baidumap provides a way to display the map is not called show and called Display it?

Baidumap This object originates from a third party and should not be changed under normal circumstances. At this point you can solve the problem by adding Baidumapadapter:

varGoogleMap ={show:function () {Console.log ('Start rendering Google Maps' ); }};varBaidumap ={display:function () {Console.log ('Start rendering Baidu map' ); }};varBaidumapadapter ={show:function () {returnBaidumap.display (); }};rendermap (GOOGLEMAP); //output: Start rendering Google MapsRendermap (Baidumapadapter);//output: Start rendering Baidu map

Let's look at another example. Suppose you are writing a page that renders a map of Beijing. Currently, all the locations in Beijing are obtained from the third party resources and their corresponding IDs are successfully rendered to the page:

varGetbeijingcity =function () {varBeijingcity =[{name:'Chaoyang', ID: One,}, {name:'Haidian', ID: A,    }    ]; returnbeijingcity;};varRender =function (FN) {Console.log ('Start rendering Beijing map' ); document.write (Json.stringify (FN ()));}; Render (getbeijingcity);

With this data, the entire page has been written, and it has been running stably online for some time. But later found that the data is not very reliable, there is still a lack of many areas. Then found on the Internet some other data resources, 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 Beijingcity = {    one,    One,    andone};

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:

varGetbeijingcity =function () {varBeijingcity =[{name:'Chaoyang', ID: One,}, {name:'Haidian', ID: A,    }    ]; returnbeijingcity;};varRender =function (FN) {Console.log ('Start rendering Beijing map' ); document.write (Json.stringify (FN ()));};varAddressadapter =function (OLDADDRESSFN) {varAddress ={}, oldaddress=OLDADDRESSFN ();  for(vari =0C c = oldaddress[i++ ]; ) {address[C.name]=c.id; }    returnfunction () {returnaddress; }};render (Addressadapter (getbeijingcity));

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

Summarize

The adapter mode is a relatively simple pair of modes. Some patterns are very similar to the structure of the adapter pattern, such as decorator mode, proxy mode, and appearance mode. These patterns belong to the "wrapper mode", which is one object that wraps another 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-Adapter mode

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.