


Detailed explanation of how to implement the adapter pattern in design patterns in JavaScript (graphic tutorial)
The adapter pattern can convert (or adjust) an interface according to needs, create another object containing the interface you need, and connect it to the object you want to change the interface to complete this conversion. Let's explain JavaScript in detail below. Methods for implementing the adapter pattern in design patterns
Sometimes during the development process, we will find that the interface required by the client is incompatible with the interface provided. Due to special reasons we cannot modify the client interface. In this case, we need to adapt existing interfaces and incompatible classes, which brings us to the adapter pattern. Through adapters, we can use them without modifying the old code. This is the power of adapters.
Adaptation mode can be used to adapt between existing interfaces and incompatible classes. Objects using this mode are also called wrappers because they are wrapping another object with a new interface. .
On the surface, the adapter pattern looks a lot like the appearance pattern. They all wrap other objects and change the interface they present. The difference between the two is how they change the interface. Facade elements present a simplified interface that provides no additional options and sometimes makes assumptions in order to facilitate the completion of common tasks. The adapter converts one interface into another interface. It does not filter out certain capabilities or simplify the interface. If the client system API is not available, an adapter is required.
Basic theory
Adapter pattern: Convert an interface into the interface required by the client without modifying the client code, so that incompatible codes can work together .
The adapter mainly consists of three roles:
(1) Client: the class that calls the interface
(2) Adapter: the class used to connect the client interface and the interface that provides services
(3) Adapter: Provides services, but the service class is incompatible with the client interface requirements.
Implementation of adapter pattern
1. The simplest adapter
The adapter pattern has no imagination It's so complicated, let's take the simplest example.
The client calls a method for addition calculation:
var result = add(1,2);
But we do not provide the add method, but provide the sum method with the same function:
function sum(v1,v2){ return v1 + v2; }
In order to avoid modifying the client and service end, we add a wrapper function:
function add (v1,v2){ reutrn sum(v1,v2); }
This is the simplest adapter pattern. We add a wrapper method between two incompatible interfaces, and use this method to connect the two to make them work together. .
2. Practical application
With the development of front-end frameworks, more and more developers are beginning to use the MVVM framework for development, and only need to operate data without When manipulating DOM elements, jQuery is becoming less and less useful. Many projects still reference the jQuery library as a tool class, because we need to use the ajax provided by jQuery to request data from the server. If jQuery's role in the project is only as an ajax tool library, it feels like killing a chicken with a powerful tool, resulting in a waste of resources. At this time we can completely encapsulate our own ajax library.
Assume that the ajax we encapsulate is used through a function:
ajax({ url:'/getData', type:'Post', dataType:'json', data:{ id:"123" } }) .done(function(){})
Except for the difference between the calling interface ajax and jQuery’s $.ajax, everything else is exactly the same.
There must be many places requesting ajax in the project. When we replace jQuery, it is impossible to modify $.ajax one by one. So what should we do? At this time, we can add an adapter:
var $ = { ajax:function (options){ return ajax(options); } }
This way It can be compatible with old code and new interfaces and avoid modification of existing code.
Summary
The principle of the adapter pattern is very simple. It is to add a new packaging class to wrap the new interface to adapt to the call of the old code and avoid modifying the interface and Calling code.
Applicable scenarios: There are many codes that call old interfaces. In order to avoid modifying old codes and replacing new interfaces, application scenarios do not affect the existing implementation.
1. Applicable occasions of adapter mode: Adapter is suitable for situations where the interface expected by the client system is incompatible with the interface provided by the existing API. The two methods adapted by the adapter should perform similar tasks, otherwise the problem will not be solved. Just like bridge elements and facade elements, by creating an adapter, you can isolate an abstraction from its implementation so that both can change independently.
2. Advantages of the adapter pattern: Use a new interface to wrap the interface of an existing class, so that the client program can use this class that is not tailor-made for it. No need for major surgery for this.
3. Disadvantages of the adapter mode: Some people think that the adapter is an unnecessary overhead that can be avoided by rewriting the existing code. In addition, the adapter pattern will also introduce a number of new tools that need to be supported. If the existing API is not yet finalized, or if the new interface is not yet finalized, the adapter may not always work.
In cases involving large systems and legacy frameworks, its advantages often outweigh its disadvantages.
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
Implementing the composition of JavaScript (detailed interpretation of BOM and DOM)
Usage and difference between some() and filter() in JavaScript arrays ( Code attached)
The above is the detailed content of Detailed explanation of how to implement the adapter pattern in design patterns in JavaScript (graphic tutorial). For more information, please follow other related articles on the PHP Chinese website!

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

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.


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

SublimeText3 English version
Recommended: Win version, supports code prompts!

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.

Dreamweaver Mac version
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
