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.
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 adapterConnect 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) } // 做一些后续的逻辑处理
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 }) }
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 }
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 } }) }
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 })
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 } }
或者在Node中的这样的例子更是常见,因为早年是没有Promise
的,所以大多数的异步由callback
来完成,且有一个约定好的规则,Error-first callback
:
const fs = require('fs') fs.readFile('test.txt', (err, data) => { if (err) // 处理异常 // 处理正确结果 })
而我们的新功能都采用了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')
因为前边也提到了,这种Error-first callback
是一个约定好的形式,所以我们可以很轻松的实现一个通用的适配器:
function promisify(func) { return (...args) => new Promise((resolve, reject) => { func(...args, (err, data) => { if (err) reject(err) resolve(data) }) }) }
然后在使用前进行对应的转换就可以用我们预期的方式来执行代码:
const fs = require('fs') const readFile = promisify(fs.readFile) await readFile('test.txt')在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!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.