JavaScript design pattern learning adapter pattern

JavaScript design pattern learning adapter pattern

Overview

The adapter pattern is a pattern in the behavioral pattern of design patterns;

definition:

Adapters are used to solve the problem of mismatch between two existing interfaces. It does not need to consider how the interface is implemented or how it should be modified in the future. Adapters do not need to modify the existing interfaces to make them work together.

Vernacular explanation:

You bought an electrical appliance and planned to take it home to experience its charm. When you took it home and planned to plug it in, you found that the appliance only supports two-hole sockets, while the power sockets in your home are all three-hole sockets. You can't go to the electrical appliance store to return the product. Suddenly, you have an idea and remember that you have a multi-function power socket at home, which happens to have three holes. So you take out your multi-function power socket and plug it into the power socket, and then plug the power socket of your electrical appliance into the two-hole socket above the multi-function socket, and start to enjoy a happy life. The multi-function socket here is an adapter.

Code Implementation

var googleMap = {
    show: function(){
        console.log('Start rendering Google Maps');
    }
};
var baiduMap = {
    show: function(){
        console.log('Start rendering Baidu Map');
    }
};
var renderMap = function( map ){
    if ( map.show instanceof Function ){
        map.show();
    }
};

renderMap( googleMap ); // Start rendering Google Map renderMap( baiduMap ); // Start rendering Baidu Map

Of course, the above code can run normally, thanks to the fact that the parameter names in the two objects are the same, so it can run and display normally;

var googleMap = {
    show: function(){
        console.log('Start rendering Google Maps');
    }
};
var baiduMap = {
    display: function(){
        console.log('Start rendering Baidu Map');
    }
};

What if the method name of baiduMap changes suddenly one day? Then if we run it as above, we will definitely get an error, because the show() method no longer exists in the baiduMap object;

Use the adapter pattern to modify:

var googleMap = {
    show: function(){
        console.log('Start rendering Google Maps');
    }
};
var baiduMap = {
    display: function(){
        console.log('Start rendering Baidu Map');
    }
};
var baiduMapAdapter = {
    show: function(){
        return baiduMap.display();

    }
};

renderMap( googleMap ); // Start rendering Google Map renderMap( baiduMapAdapter ); // Start rendering Baidu Map

In this code, the adapter does something very simple. It creates an object, adds a show() method with the same name, and then calls the baiduMap.display() method in the adapter. In this way, we only need to call our adapter when calling baiduMap to achieve the desired effect.

As front-end developers, we must have a better understanding of the data and data format expected on the page, but in the development model with front-end and back-end separation, we sometimes encounter this embarrassing situation:

We all know that many UI components or tool libraries will render according to the specified data format, but the backend does not know this at this time; so we may not be able to directly render the data from the interface on the page normally, and at this time the boss urges us to go online quickly, but the backend insists that the data format is fine and refuses to modify it; at this time we can use the adapter mode to format the data on the front end;

The json data format returned by the backend is:

[
  {
    "day": "Monday",
    "uv": 6300
  },
  {
    "day": "Tuesday",
    "uv": 7100
  }, {
    "day": "Wednesday",
    "uv": 4300
  }, {
    "day": "Thursday",
    "uv": 3300
  }, {
    "day": "Friday",
    "uv": 8300
  }, {
    "day": "Saturday",
    "uv": 9300
  }, {
    "day": "Sunday",
    "uv": 11300
  }
]

Echarts chart graphics require data format:

["Tuesday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] //x-axis data [6300. 7100, 4300, 3300, 8300, 9300, 11300] //coordinate point data

Even though it hurts, we still have to solve the problem! Use an adapter to solve:

//x-axis adapter function echartXAxisAdapter(res) {
  return res.map(item => item.day);
}

//Coordinate point adapter function echartDataAdapter(res) {
  return res.map(item => item.uv);
}

The problem can be solved by creating two functions to format the data according to the data format required by echarts. These two methods are actually an adapter. By throwing the specified data into it, we can output the data format we expect according to the specified rules.

Summarize

I personally think that the adapter pattern is actually a design pattern that is used to make up for the loss. If we know the expected data format or method name at the beginning of the project development, we may never use the adapter pattern. However, the iteration of the project is often unpredictable. When the data format or method name changes after the project iteration, we can usually use the adapter pattern to adapt and solve it. Of course, the best solution is to negotiate and discuss the code specifications such as data format and file name between the front-end and back-end during the project development process, which will greatly improve the development efficiency of the project.

The above is the details of the adapter pattern in JavaScript design pattern learning. For more information about JavaScript design patterns, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • JavaScript Composite Pattern
  • JavaScript programming design pattern: Observer Pattern (Observer Pattern) example detailed explanation
  • JavaScript Design Patterns – Adapter Pattern Principles and Application Examples
  • Detailed explanation of the principles and usage examples of JavaScript adapter pattern
  • JavaScript Adapter Pattern Explained
  • Summary of NodeJS design patterns [singleton pattern, adapter pattern, decorator pattern, observer pattern]
  • Adapter pattern in javascript design pattern [Adapter pattern] implementation example
  • Understanding the Adapter Pattern in JavaScript

<<:  mysql5.7.17 installation and configuration example on win2008R2 64-bit system

>>:  Install Docker on Linux (very simple installation method)

Recommend

Solution to CSS flex-basis text overflow problem

The insignificant flex-basis has caused a lot of ...

js implements mouse in and out card switching content

This article shares the specific code of js to re...

TABLE tags (TAGS) detailed introduction

Basic syntax of the table <table>...</tab...

Several ways to set the expiration time of localStorage

Table of contents Problem Description 1. Basic so...

Summary of some tips on MySQL index knowledge

Table of contents 1. Basic knowledge of indexing ...

Explanation of several ways to run Tomcat under Linux

Starting and shutting down Tomcat under Linux In ...

Solution for Tomcat to place configuration files externally

question When we are developing normally, if we w...

How to deploy python crawler scripts on Linux and set up scheduled tasks

Last year, due to project needs, I wrote a crawle...

How to install theano and keras on ubuntu system

Note: The system is Ubuntu 14.04LTS, a 32-bit ope...

Quick understanding and example application of Vuex state machine

Table of contents 1. Quick understanding of conce...

Super detailed steps to install zabbix3.0 on centos7

Preface Recently, part of the company's busin...

The difference and choice between datetime and timestamp in MySQL

Table of contents 1 Difference 1.1 Space Occupanc...

Vue implements setting multiple countdowns at the same time

This article example shares the specific code of ...