Home > Web Front-end > JS Tutorial > Application of adapter in JavaScript (with examples)

Application of adapter in JavaScript (with examples)

不言
Release: 2018-09-19 15:08:40
Original
1576 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template