search
HomeWeb Front-endJS TutorialA brief introduction to JavaScript design patterns adapter pattern

Adapter mode (Adapter)

The adapter mode is mainly used to solve the problem of mismatch between two existing interfaces. It does not consider how these interfaces are implemented. , without considering how they might evolve in the future. The adapter pattern enables existing interfaces to work together without changing them.

The alias of the adapter is wrapper (wrapper), which is a relatively simple pattern. There are many scenarios in program development: when we try to call an interface of a module or object, we find that the format of the interface does not meet the current needs. There are two solutions at this time. The first is to modify the original interface implementation. However, if the original module is very complex, or the module we get is a compressed code written by someone else, modifying the original interface is not realistic. . The second method is to create an adapter to convert the original interface into another interface that the customer wants. The customer only needs to deal with the adapter.

There are many examples of adapters in reality: power sockets, USB adapters, etc.; for example, the headphone jack after iPhone 7 has changed from a 3.5mm round hole interface to Apple’s exclusive lightning interface. Many people need an adapter below for their previous round-hole headphones to listen to music on their newly purchased iPhone.

2. Adapter mode usage scenario

2.1 Interface adaptation

When we apply to googleMap and baiduMapWhen both issue "display" requests, googleMap and baiduMap` display the map on the page in their own ways

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

renderMap(googleMap); // 输出:开始渲染谷歌地图renderMap(baiduMap);  // 输出:开始渲染百度地图

The key to the smooth operation of this program is googleMap and baiduMap provide the same show method, but the third-party interface method is not within our own control. If baiduMap The method provided to display the map is not called show but called display?

baiduMap This object comes from a third party. Under normal circumstances, we should not change it, and sometimes we cannot change it. At this time we can solve the problem by adding baiduMapAdapter:

const googleMap = {
  show: function () {
    console.log('开始渲染谷歌地图');
  }
};const baiduMap = {
  display: function () {
    console.log('开始渲染百度地图');
  }
};const baiduMapAdapter = {
  show: function(){
    return baiduMap.display();
  }
};

renderMap(googleMap);       // 输出:开始渲染谷歌地图renderMap(baiduMapAdapter); // 输出:开始渲染百度地图

2.2 Adaptation of parameters

In some cases, a method may need to pass in multiple parameters, for example When doing some monitoring and reporting SDK, a lot of data may be collected. There is a systemInfo in this class, and five parameters need to be passed in to receive relevant information about the mobile phone:

class SDK {
  systemInf(brand, os, carrier, language, network) {    //dosomething.....
  }
}

Usually when the incoming parameters are greater than 3, we can consider merging the parameters into one object, just like what we do in $.ajax. Below we can define the parameter interface of systemInfo as follows (String represents the parameter type, ?: represents the optional option)

{
  brand: String
  os: String
  carrier:? String
  language:? String
  network:? String}

As can be seen, carrier, language, network These three properties do not have to be passed in, they may be set to some default values ​​inside the method. So at this time we can use an adapter inside the method to adapt to this parameter object. This method is common in our plug-ins or npm packages;

class SDK {
  systemInf(config) {    let defaultConfig = {
      brand: null,  //手机品牌
      os: null, //系统类型: Andoird或 iOS
      carrier: 'china-mobile', //运营商,默认中国移动
      language: 'zh', //语言类型,默认中文
      network: 'wifi', //网络类型,默认wifi
    }    //参数适配
    for( let i in config) {
      defaultConfig[i] = config[i] || defaultConfig[i];
    }    //dosomething.....
  }
}

2.3 Data Adaptation

Data adaptation is the most common scenario in the front end. At this time, the adapter is It is of great significance to solve the data dependence of front-end and back-end. Usually the data passed by the server is inconsistent with the data format we need to use on the front end. Especially when using some UI frameworks, the data specified by the framework has a fixed format. Therefore, at this time we need to adapt the back-end data format.

For example, there is a weekly uv on the website using Echarts line chart. Usually the data format returned by the backend is as follows:

[
  {    "day": "周一",    "uv": 6300
  },
  {    "day": "周二",    "uv": 7100
  },  {    "day": "周三",    "uv": 4300
  },  {    "day": "周四",    "uv": 3300
  },  {    "day": "周五",    "uv": 8300
  },  {    "day": "周六",    "uv": 9300
  }, {    "day": "周日",    "uv": 11300
  }
]

But the x-axis data format required by Echarts is as follows: The coordinate point data looks like this:

["周二", "周二", "周三", "周四", "周五", "周六", "周日"] //x轴的数据[6300. 7100, 4300, 3300, 8300, 9300, 11300] //坐标点的数据

So we can use an adapter to adapt the back-end return data:

//x轴适配器function echartXAxisAdapter(res) {
  return res.map(item => item.day);
}//坐标点适配器function echartDataAdapter(res) {
  return res.map(item => item.uv);
}

3 Summary

Adapter pattern is a pair of relatively simple patterns. However, the adapter pattern has many usage scenarios in JS. In terms of parameter adaptation, many libraries and frameworks use the adapter pattern; data adaptation is very important in solving front-end and back-end data dependencies. What we need to realize is that the adapter mode is essentially a "make up for it" mode. It solves the problem of incompatibility between the two existing interfaces. You should not use this mode in the early development stage of the software; if At the beginning of the design, we can plan the consistency of the interface as a whole, so the adapter should be used as little as possible.

Adapters in JavaScript are more used between objects. In order to make the object available, we usually split and reassemble the object, so we must understand the internal structure of the adapting object, which is also the The difference between appearance mode is, of course, that the allocation mode also solves the coupling between objects. The packaged adaptation code increases some resource consumption, but this is minimal.

Related articles:

Design Pattern (Adapter)

JavaScript Design Pattern Series Five: Adapter Pattern

The above is the detailed content of A brief introduction to JavaScript design patterns adapter pattern. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software