Article series
A singleton of javascript design patterns
Adapter pattern for javascript design pattern
Decorator pattern for javascript design pattern
Javascript design pattern proxy pattern
Comparison of javascript adaptation, proxy, and decorator patterns
Javascript design pattern state pattern
Iterator pattern for javascript design pattern
Javascript design pattern strategy pattern
Javascript design pattern observer pattern
Publish subscriber pattern for javascript design pattern
concept
Adapter pattern: Converts the interface (method or property) of one class (object) into another interface (method or property) that the customer expects, so that classes (object) that would otherwise not work together due to incompatible interfaces can work together. Simply put, it is a “converter” designed for compatibility.
In this paper, the code
Adapters in Life
For example, in life to Hong Kong or abroad, the power interface is different from the domestic need a converterAnother example is the Type-C interface. I used to use round head headphones until I recently bought a Mi 10 phone and found that its phone hole was square. Fortunately, the manufacturer sent me a converter so that I could continue to listen to music
By definition,
- Class: Mi 10
- Class interface: square
- Client (me)
- Another interface: circular
Business scenarios for adapters
Plug converter
class Adapter {
specificRequest() {
return German standard plug}}class Target {
constructor() {
this.adapter = new Adapter()
}
request() {
let info = `The ${this.adapter.specificRequest()}-- Convert to -- Chinese plug
return info
}
}
let target = new Target()
console.info(target.request())
Copy the code
Adaptation between map interfaces
var googleMap = {
show: function () {
// The method is show
console.log('Start rendering Google Maps')}}var baiduMap = {
display: function () {
// The method is display
console.log('Start rendering baidu Map')}}var baiduMapAdapter = {
show: function () {
// The adapter is also changed to show, which returns display
return baiduMap.display()
}
}
// Here is how to render the map, passing in the map object
var renderMap = function (map) {
// Pass in the map object
if (map.show instanceof Function) {
/ / determine
map.show() // Show method for map objects
// Call show when the baiduMapAdapter object is passed in
// This is the display method of baiduMap.
}
}
renderMap(googleMap) // Output: Start rendering Google Maps
renderMap(baiduMapAdapter) // Output: Start rendering Baidu map
Copy the code
Compatible interface request
export default class HttpUtils {
/ / get methods
static get(url) {
return new Promise((resolve, reject) = > {
/ / call the fetch
fetch(url)
.then(response= > response.json())
.then(result= > {
resolve(result)
})
.catch(error= > {
reject(error)
})
})
}
// The data is passed in as an object
static post(url, data) {
return new Promise((resolve, reject) = > {
/ / call the fetch
fetch(url, {
method: 'POST'.headers: {
Accept: 'application/json'.'Content-Type': 'application/x-www-form-urlencoded'
},
// Format data of type Object as a valid body argument
body: this.changeData(data)
})
.then(response= > response.json())
.then(result= > {
resolve(result)
})
.catch(error= > {
reject(error)
})
})
}
// body Requests the formatting method of the body
static changeData(obj) {
var prop,
str = ' '
var i = 0
for (prop in obj) {
if(! prop) {return
}
if (i == 0) {
str += prop + '=' + obj[prop]
} else {
str += '&' + prop + '=' + obj[prop]
}
i++
}
return str
}
}
Copy the code
When you want to use fetch to initiate a request, you just need to call it as follows:
// Define the destination URL address
const URL = "xxxxx"
// Define the POST entry parameter
const params = {
...
}
// Initiate a POST request
const postResponse = await HttpUtils.post(URL,params) || {}
// Initiate a GET request
const getResponse = await HttpUtils.get(URL)
Copy the code
But there are some old interface calls in the project, such as the following:
// Send a get request
Ajax('get', URL address, post entry parameter,function(data){
// Successful callback logic
}, function(error){
// Failed callback logic
})
Copy the code
To smooth out the differences, the adapter pattern can be used
// Ajax adaptor functions that are used to participate in the old interface remain the same
async function AjaxAdapter(type, url, data, success, failed) {
const type = type.toUpperCase()
let result
try {
// All actual requests are initiated by the new interface
if(type === 'GET') {
result = await HttpUtils.get(url) || {}
} else if(type === 'POST') {
result = await HttpUtils.post(url, data) || {}
}
// Assume that the status code corresponding to a successful request is 1
result.statusCode === 1 && success ? success(result) : failed(result.statusCode)
} catch(error) {
// Catch network errors
if(failed){ failed(error.statusCode); }}}// Use an adapter to accommodate older Ajax methods
async function Ajax(type, url, data, success, failed) {
await AjaxAdapter(type, url, data, success, failed)
}
Copy the code
In this way, an AjaxAdapter is used to take over the parameters of the old interface, achieving seamless connection between the old and new interfaces.
Scenarios using the adapter pattern
Application of jQuery
The adapter pattern is ideal for cross-browser compatibility, such as the powerful jQuery adapter that encapsulates event handling to address cross-browser compatibility issues.
// $('selector').on
function on(target, event, callback) {
if (target.addEventListener) {
// Standard event listener
target.addEventListener(event, callback);
} else if (target.attachEvent) {
// Listen for events of earlier versions of IE
target.attachEvent(event, callback)
} else {
// Lower version browser event listener
target[`on${event}`] = callback
}
}
Copy the code
Refer to the link
Core principles and application practice of JavaScript design pattern
conclusion
Your “like” is the biggest affirmation for me, if you feel helpful, please leave your appreciation, thank you!!