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

Alibaba Cloud Centos7.3 installation mysql5.7.18 rpm installation tutorial

Uninstall MariaDB CentOS7 installs MariaDB instea...

TABLE tags (TAGS) detailed introduction

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

CSS animation property usage and example code (transition/transform/animation)

During development, a good user interface will al...

Summarize the User-Agent of popular browsers

1. Basic knowledge: Http Header User-Agent User A...

Undo log in MySQL

Concept introduction: We know that the redo log i...

CSS to achieve fast and cool shaking animation effect

1. Introduction to Animate.css Animate.css is a r...

Ubuntu 20.04 how to modify the IP address example

illustrate: Today, when continuing the last offic...

How to view MySQL links and kill abnormal links

Preface: During database operation and maintenanc...

Implementation of static website layout in docker container

Server placement It is recommended to use cloud s...

CSS3 to achieve dynamic background gradient effect

Learning CSS3 is more about getting familiar with...

Axios secondary encapsulation example Demo in the project

1. Why do packaging? Facilitates overall code cal...