Table of Contents
Examples in life
Reflected in the code
Connect to multiple third-party SDK
Some other examples
小结
Home Web Front-end JS Tutorial Application of adapter in JavaScript (with examples)

Application of adapter in JavaScript (with examples)

Sep 19, 2018 pm 03:08 PM
javascript node.js

The content of this article is about the application of adapters in JavaScript (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

The adapter design pattern is very useful in JavaScript. It can be seen in dealing with cross-browser compatibility issues and integrating calls from multiple third-party SDKs.
In fact, in daily development, we often inadvertently write code that conforms to a certain design pattern. After all, design patterns are some templates summarized and refined by seniors that can help improve development efficiency. They originate from daily development. middle.
The adapter should actually be a relatively common one in JavaScript.

In Wikipedia, the definition of the adapter pattern is:

In software engineering, the adapter pattern is a software design pattern that allows the interface of an existing class to be used from another interface. It is often used to make existing classes work with other classes without modifying their source code.

Examples in life

The most common thing in life is the power plug adapter. The socket standards of various countries in the world are different. If you need to purchase the corresponding power plug according to the standards of each country, then It would be too much of a waste of money. It would definitely be unrealistic to bring the socket and smash the walls of other people's homes and rewire them.
So there will be a plug adapter, which is used to convert one type of plug into another type of plug. This thing that is a transfer between the socket and your power supply is the adapter.

Application of adapter in JavaScript (with examples)

Reflected in the code

But when it comes to programming, I personally understand it this way:

Convert those If you hide the dirty code that you don’t want to see, you can say that this is an adapter

Connect to multiple third-party SDK

As an example in daily development, we are developing a WeChat public account , WeChat’s payment module is used in it. After a long period of joint debugging, the entire process has finally been run through. Just when you are ready to happily package and launch the code, you get a new requirement:
We need to access The SDK of Alipay official account must also have a payment process

In order to reuse the code, we may write such logic in the script:

if (platform === 'wechat') {
  wx.pay(config)
} else if (platform === 'alipay') {
  alipay.pay(config)
}

// 做一些后续的逻辑处理
Copy after login

But generally speaking, The interface calling methods provided by each manufacturer's SDK will be somewhat different. Although sometimes the same document may be used, thanks to friends.

So the above code may look like this:

// 并不是真实的参数配置,仅仅举例使用
const config = {
  price: 10,
  goodsId: 1
}

// 还有可能返回值的处理方式也不相同
if (platform === 'wechat') {
  config.appId = 'XXX'
  config.secretKey = 'XXX'
  wx.pay(config).then((err, data) => {
    if (err) // error

    // success
  })
} else if (platform === 'alipay') {
  config.token = 'XXX'
  alipay.pay(config, data => {
    // success
  }, err => {
    // error
  })
}
Copy after login

For now, the code interface is quite clear. As long as we write good comments, this is not too bad. code.
But life is always full of surprises, and we have received requests to add QQ’s SDK, Meituan’s SDK, Xiaomi’s SDK, or some banks’ SDK.

At this time your code may look like this:

switch (platform) {
  case 'wechat':
    // 微信的处理逻辑
  break
  case 'QQ':
    // QQ的处理逻辑
  break
  case 'alipay':
    // 支付宝的处理逻辑
  break
  case 'meituan':
    // 美团的处理逻辑
  break
  case 'xiaomi':
    // 小米的处理逻辑
  break
}
Copy after login

This is no longer a problem that some comments can make up for. Such code will become more and more difficult to maintain, and various SDKs are full of strange things. Calling method, if others have similar needs and need to rewrite such code, it will definitely be a waste of resources.

So in order to ensure the clarity of our business logic, and to avoid future generations stepping on this pitfall repeatedly, we will split it out and exist as a public function:
Find one of them The calling method of the SDK or a rule we have agreed upon is used as a benchmark.
Let's tell the caller what you want to do, how you can get the return data, and then we make these various dirty judgments inside the function:

function pay ({
  price,
  goodsId
}) {
  return new Promise((resolve, reject) => {
    const config = {}

    switch (platform) {
      case 'wechat':
        // 微信的处理逻辑
        config.price = price
        config.goodsId = goodsId
        config.appId = 'XXX'
        config.secretKey = 'XXX'
        wx.pay(config).then((err, data) => {
          if (err) return reject(err)

          resolve(data)
        })
      break
      case 'QQ':
        // QQ的处理逻辑
        config.price = price * 100
        config.gid = goodsId
        config.appId = 'XXX'
        config.secretKey = 'XXX'
        config.success = resolve
        config.error = reject
        qq.pay(config)
      break
      case 'alipay':
        // 支付宝的处理逻辑
        config.payment = price
        config.id = goodsId
        config.token = 'XXX'
        alipay.pay(config, resolve, reject)
      break
    }
  })
}
Copy after login

In this way, no matter what environment we are in , as long as our adapter supports it, it can be called according to the general rules we agreed on, and what SDK is specifically executed is something that the adapter needs to care about:

// run anywhere
await pay({
  price: 10,
  goodsId: 1
})
Copy after login

For the SDK provider, you only need to know Some parameters you need, and then return the data in your own way.
For the SDK call room, we only need the common parameters that we have agreed upon, and the monitoring callback processing in the agreed way.

The task of integrating multiple third-party SDKs is left to the adapter. Then we compress and obfuscate the adapter code and put it in an invisible corner. Such code logic will become very complicated. Cleared up :).

This is roughly the role of adapters. One thing must be clear. Adapters are not silver bullets. Those cumbersome codes always exist, but you can’t see them when writing business. __,Out of sight out of mind.

Some other examples

Personally feel that there are many adapter examples in jQuery, including the most basic $('selector').on, isn't this an obvious adapter pattern?

Downgrade step by step and smooth out some differences between browsers, allowing us to perform event monitoring in mainstream browsers through a simple on:

// 一个简单的伪代码示例
function on (target, event, callback) {
  if (target.addEventListener) {
    // 标准的监听事件方式
    target.addEventListener(event, callback)
  } else if (target.attachEvent) {
    // IE低版本的监听方式
    target.attachEvent(event, callback)
  } else {
    // 一些低版本的浏览器监听事件方式
    target[`on${event}`] = callback
  }
}
Copy after login

或者在Node中的这样的例子更是常见,因为早年是没有Promise的,所以大多数的异步由callback来完成,且有一个约定好的规则,Error-first callback

const fs = require('fs')

fs.readFile('test.txt', (err, data) => {
  if (err) // 处理异常

  // 处理正确结果
})
Copy after login

而我们的新功能都采用了async/await的方式来进行,当我们需要复用一些老项目中的功能时,直接去修改老项目的代码肯定是不可行的。  
这样的兼容处理需要调用方来做,所以为了让逻辑代码看起来不是太混乱,我们可能会将这样的回调转换为Promise的版本方便我们进行调用:

const fs = require('fs')

function readFile (fileName) {
  return new Promise((resolve, reject) => {
    fs.readFile(fileName, (err, data) => {
      if (err) reject(err)

      resolve(data)
    })
  })
}

await readFile('test.txt')
Copy after login

因为前边也提到了,这种Error-first callback是一个约定好的形式,所以我们可以很轻松的实现一个通用的适配器:

function promisify(func) {
  return (...args) => new Promise((resolve, reject) => {
    func(...args, (err, data) => {
      if (err) reject(err)

      resolve(data)
    })
  })
}
Copy after login

然后在使用前进行对应的转换就可以用我们预期的方式来执行代码:

const fs = require('fs')

const readFile = promisify(fs.readFile)

await readFile('test.txt')
Copy after login
在Node8中,官方已经实现了类似这样的工具函数:util.promisify

小结

个人观点:所有的设计模式都不是凭空想象出来的,肯定是在开发的过程中,总结提炼出的一些高效的方法,这也就意味着,可能你并不需要在刚开始的时候就去生啃这些各种命名高大上的设计模式。  
因为书中所说的场景可能并不全面,也可能针对某些语言,会存在更好的解决办法,所以生搬硬套可能并不会写出有灵魂的代码 :)

The above is the detailed content of Application of adapter in JavaScript (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

See all articles