Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the seven design patterns of JavaScript?

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

What are the seven design patterns of JavaScript, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can gain something.

When starting a new project, we shouldn't start programming right away. Instead, you should first define the purpose and scope of the project, and then list its functions or specifications. If you have started programming or are working on a complex project, you should choose a design pattern that works best for your project.

What is a design pattern?

In software engineering, design patterns are reusable solutions to common problems in software design. Design patterns are also a best practice for experienced developers to address specific issues. It can be used as a template for programming.

Why use design patterns?

Many engineers either think that design patterns are a waste of time or do not know how to use design patterns properly. But if the design pattern is used correctly, it can help you write better readable code, and the code is easier to maintain and understand.

Most importantly, design patterns provide a common vocabulary for software developers. They allow people who learn your code to quickly understand the intent of the code. For example, if you use the decorator pattern in your project, new developers can quickly know what this code does, so they can focus more on solving business problems than trying to understand what the code is doing.

Now that we know what a design pattern is and its importance, let's take a closer look at the seven design patterns in JavaScript.

1. Module mode

The module is a separate piece of code, so we can update the module without affecting the rest of the code. The module also allows us to avoid namespace contamination by creating separate scopes for variables. When they are decoupled from other code, we can also reuse modules in other projects.

Modules are an integral part of any modern JavaScript application and help keep your code clean, independent, and organized. There are many ways to create modules in JavaScript, one of which is module mode.

Unlike other programming languages, JavaScript does not have access modifiers, that is, you cannot declare variables private or public. Therefore, the module mode can also be used to simulate the concept of encapsulation.

The module pattern uses IIFE (immediately called function expressions), closures, and function scopes to simulate the concept of encapsulation. For example:

Const myModule = (function () {const privateVariable = 'Hello World'; function privateMethod () {console.log (privateVariable);} return {publicMethod: function () {privateMethod ();}) (); myModule.publicMethod ()

Because it is IIFE, the code is executed immediately and the return object is assigned to the myModule variable. Because of closures, even after the IIFE is complete, the returned objects can still access functions and variables defined within IIFE.

Therefore, variables and functions defined within IIFE are invisible to the outside, making them private members of the myModule module.

After the code is executed, the myModule variable looks like this:

Const myModule = {publicMethod: function () {privateMethod ();}}

So when we call publicMethod (), it will call privateMethod () for example:

/ / Prints' Hello World' module.publicMethod (); 2. Reveal the module mode

Revealing the module pattern is a slight improvement to the module pattern by Christian Heilmann. The problem with the module pattern is that we have to create new public functions to call private functions and variables.

In this mode, we map the properties of the returned object to the private function to be exposed. This is why it is called the reveal module mode. For example:

Const myRevealingModule = (function () {let privateVar = 'Peter'; const publicVar =' Hello World'; function privateFunction () {console.log ('Name:' + privateVar);} function publicSetName (name) {privateVar = name;} function publicGetName () {privateFunction ();} / * reveal methods and variables by assigning them to object properties * / return {setName: publicSetName, greeting: publicVar, getName: publicGetName} }) (); myRevealingModule.setName ('Mark'); / / prints Name: Mark myRevealingModule.getName ()

This pattern makes it easier for us to know which functions and variables are public, virtually improving the readability of the code. After executing the code, the myRevealingModule looks like the following:

Const myRevealingModule = {setName: publicSetName, greeting: publicVar, getName: publicGetName}

When we call myRevealingModule.setName ('Mark'), we actually call the internal publicSetName. When myRevealingModule.getName () is called, the internal publicGetName is actually called, for example:

MyRevealingModule.setName ('Mark'); / / prints Name: Mark myRevealingModule.getName ()

Compared with the module mode, the advantages of revealing the module mode are:

By modifying a line in the return statement, we can change the member from public to private, and vice versa.

The returned object does not contain any function definitions, and all right expressions are defined in IIFE, making the code clear and readable.

Third, ES6 module

Before ES6, JavaScript had no built-in modules, so developers had to rely on third-party libraries or module patterns to implement modules. But since ES6,JavaScript has built-in modules.

The modules of ES6 are stored as files. There can be only one module per file. By default, everything within the module is private. Expose functions, variables, and classes by using the export keyword. The code within the module always runs in strict mode.

3.1 Export Modul

There are two ways to export function and variable declarations:

Add the export keyword before function and variable declarations. For example:

/ / utils.js export const greeting = 'Hello World'; export function sum (num1, num2) {console.log (' Sum:', num1, num2); return num1 + num2;} export function subtract (num1, num2) {console.log ('Subtract:', num1, num2); return num1-num2;} / / This is a private function function privateLog () {console.log (' Private Function');}

Add the export keyword at the end of the code to expose functions and variables. For example:

/ utils.js function multiply (num1, num2) {console.log ('Multiply:', num1, num2); return num1 * num2;} function divide (num1, num2) {console.log (' Divide:', num1, num2); return num1 / num2;} / / This is a private function function privateLog () {console.log ('Private Function');} export {multiply, divide}

3.2 Import module

Similar to the export module, there are two ways to import the module using the import keyword. For example:

Import multiple projects at a time

/ / main.js / / importing multiple items import {sum, multiply} from'. / utils.js'; console.log (sum (3,7)); console.log (multiply (3,7))

Import all modules

/ / main.js / / importing all of module import * as utils from'. / utils.js'; console.log (utils.sum (3,7)); console.log (utils.multiply (3,7))

3.3 use aliases in import and export

Rename export

/ utils.js function sum (num1, num2) {console.log ('Sum:', num1, num2); return num1 + num2;} function multiply (num1, num2) {console.log (' Multiply:', num1, num2); return num1 * num2;} export {sum as add, multiply}

Rename Import

/ / main.js import {add, multiply as mult} from'. / utils.js'; console.log (add (3,7)); console.log (mult (3,7)); IV. Singleton mode

A singleton object is an object that can only be instantiated once. If it does not exist, the singleton pattern creates a new instance of the class. If an instance exists, only a reference to the object is returned. Calling the constructor repeatedly will always get the same object.

JavaScript has always been a language with built-in singletons. We just don't call them singletons, we call them object literals. For example:

Const user = {name: 'Peter', age: 25, job:' Teacher', greet: function () {console.log ('hellograms');}}

Because each object in JavaScript occupies a unique memory location, and when we call the user object, we are actually returning a reference to that object.

If we try to copy the user variable to another variable and modify it. For example:

Const user1 = user; user1.name = 'Mark'

We will see that both objects are modified because objects in JavaScript are passed by reference rather than by value. Therefore, there is only one object in memory. For example:

/ / prints' Mark' console.log (user.name); / / prints' Mark' console.log (user1.name); / / prints true console.log (user = user1)

You can use constructors to implement singleton patterns. For example:

Let instance = null; function User () {if (instance) {return instance;} instance = this; this.name = 'Peter'; this.age = 25; return instance;} const user1 = new User (); const user2 = new User (); / / prints true console.log (user1 = user2)

When this constructor is called, it checks to see if the instance object exists. If the object does not exist, the this variable is assigned to the instance variable. If the object exists, only the object is returned.

Singletons can also be implemented using module mode. For example:

Const singleton = (function () {let instance; function init () {return {name: 'Peter', age: 24,};} return {getInstance: function () {if (! instance) {instance = init ();} return instance;}}) (); const instanceA = singleton.getInstance (); const instanceB = singleton.getInstance () / / prints true console.log (instanceA = instanceB)

In the above code, we create a new instance by calling the singleton.getInstance method. If the instance already exists, this method returns only that instance. If the instance does not exist, create a new instance by calling the init () function.

V. Factory model

The factory pattern uses the factory method to create objects without specifying a specific class or constructor pattern.

The factory pattern is used to create objects without exposing the instantiation logic. We can use this pattern when we need to generate different objects according to specific conditions. For example:

Class Car {constructor (options) {this.doors = options.doors | | 4; this.state = options.state | | 'brand new'; this.color = options.color | |' white';}} class Truck {constructor (options) {this.doors = options.doors | | 4; this.state = options.state | | 'used'; this.color = options.color | |' black' | }} class VehicleFactory {createVehicle (options) {if (options.vehicleType = 'car') {return new Car (options);} else if (options.vehicleType =' truck') {return new Truck (options);}

Here, a Car and a Truck class (with some default values) are created, which are used to create new car and truck objects. And a VehicleFactory class is defined to create and return new objects based on the vehicleType property in the options object.

Const factory = new VehicleFactory (); const car = factory.createVehicle ({vehicleType: 'car', doors: 4, color:' silver', state: 'Brand New'}); const truck= factory.createVehicle ({vehicleType:' truck', doors: 2, color: 'white', state:' used'}); / / Prints Car {doors: 4, state: "Brand New", color: "silver"} console.log (car) / / Prints Truck {doors: 2, state: "used", color: "white"} console.log (truck)

I created a new factory object for the class VehicleFactory. We then create a new Car or Truck object by calling the factory.createVehicle method and passing the options object, whose vehicleType property may be car or truck.

VI. Decorator mode

The decorator pattern is used to extend the functionality of objects without modifying existing classes or constructors. This mode can be used to add features to objects without modifying the underlying code.

A simple example of this pattern is:

Function Car (name) {this.name = name; / / Default values this.color = 'White';} / / Creating a new Object to decorate const tesla= new Car (' Tesla Model 3'); / / Decorating the object with new functionality tesla.setColor = function (color) {this.color = color;} tesla.setPrice = function (price) {this.price = price;} tesla.setColor ('black'); tesla.setPrice (49000); / / prints black console.log (tesla.color)

A more practical example of this pattern is:

Assume that the cost of a car depends on the number of functions it has. Without the decorator pattern, we would have to create different classes for different combinations of functions, each with a cost method to calculate the cost. For example:

Class Car () {} class CarWithAC () {} class CarWithAutoTransmission {} class CarWithPowerLocks {} class CarWithACandPowerLocks {}

However, through the decorator pattern, we can create a base class car and add corresponding cost logic to different objects through the decorator function.

Class Car {constructor () {/ / Default Cost this.cost = function () {return 20000;} / / Decorator function function carWithAC (car) {car.hasAC = true; const prevCost = car.cost (); car.cost = function () {return prevCost + 500;} / Decorator function function carWithAutoTransmission (car) {car.hasAutoTransmission = true; const prevCost = car.cost () Car.cost = function () {return prevCost + 2000;}} / / Decorator function function carWithPowerLocks (car) {car.hasPowerLocks = true; const prevCost = car.cost (); car.cost = function () {return prevCost + 500;}}

First of all, we created the base class Car of the car. Then a decorator is created for the property to be added and this decorator takes a Car object as a parameter. The cost function of the object is then overridden by returning the updated car cost, and an attribute is added to identify whether a property has been added.

To add new features, we just need to do something like this:

Const car = new Car (); console.log (car.cost ()); carWithAC (car); carWithAutoTransmission (car); carWithPowerLocks (car)

Finally, we can calculate the cost of the car like this:

/ / Calculating total cost of the car console.log (car.cost ())

We have learned about the various design patterns used in JavaScript, but there are no design patterns that can be implemented in JavaScript.

While it is important to understand the various design patterns, it is also important not to overuse them. Before using a design pattern, you should carefully consider whether your question is suitable for the design pattern. To know whether a pattern is suitable for your problem, you should study the design pattern and its application.

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report