Singleton design pattern in JavaScript

Singleton design pattern in JavaScript

Preface:

Design patterns are very important in our programming!

Design patterns represent best practices that are commonly adopted by experienced object-oriented software developers. Design patterns are solutions to common problems faced by software developers during the software development process. These solutions are the result of trial and error by numerous software developers over a considerable period of time.

I'm currently learning design patterns, would you guys like to join me?

1. What is a design pattern?

In software design, a concise and elegant solution to a specific problem.

Summarizing previous experience and applying it reasonably to a certain scenario can solve practical problems.

2. Five design principles of design pattern (SOLID)

S-Single Responsibility Principle

That is, a program only does one thing well.

O-Open Closed Principle

Open to extension, closed to modification

L-Liskov substitution principle

Subclasses can override parent classes and appear where parent classes appear.

I-Interface independence principle

Keep the interface single and independent

D-Dependency leads to principle

The usage method only focuses on the interface and not the implementation of the specific class

3. Why do we need design patterns?

Readability

Using design patterns can improve our code readability and improve subsequent development efficiency

Scalability

Using design patterns to decouple code can greatly enhance the code's modifiability and extensibility.

Reusability

Using design patterns allows you to reuse existing solutions without having to repeat the same work

reliability

Using design patterns can increase the robustness of the system and make code writing truly engineering-oriented.

4. Singleton Pattern

Definition: Unique & globally accessible. Ensure that a class has only one instance and provide a global access point to it.

Another multi-instance pattern is to construct multiple different instances through one class. This is the multi-instance pattern.

The most essential difference between the singleton mode and the multi-instance mode: the number of instances.

The singleton pattern always has only one instance, which can be cached and reused.

Application scenario: content that can be cached, such as a login pop-up window.

I think if this is a place that can be used twice or more in your project, you can try this, which can reduce a lot of code.

Let’s look at this pseudocode:

const creatLoginLayer = () => {
    const div = document.createElement("div");
    div.innerHtml = "Login floating window";
    div.style.display = "none";
    document.body.appendChild(div);
    return div;
};

document.getElementById("loginBtn").onclick = () => {
    const loginLayer = creatLoginLayer();
    loginLayer.style.display = "block";
};

The function of creatLoginLayer is to create a login pop-up window and add the node to body . The following is a click event of the login button. Clicking the login button will create a login pop-up window and change display from none to block to display it.

There is nothing wrong with this logic, but think about it, these codes will be executed every time the login button is clicked. What if there are many places in a project that need this? The lines we have above are just a few short lines. What if there are hundreds, thousands or even tens of thousands? Isn't it a great loss of performance? At this time, our singleton mode comes in handy.

After using the singleton pattern:

const getSingle = (fn) => {
    let result;
    return (...rest) => {
        return result || (result = fn.apply(this.rest));
    };
};

const creatLoginLayer = () => {
    const div = document.createElement("div");
    div.innerHtml = "Login floating window";
    div.style.display = "none";
    document.body.appendChild(div);
    return div;
};

const createSingleLoginLayer = getSingle(createLoginLayer);

document.getElementById("loginBtn").onclick = () => {
    const loginLayer = createSingleLoginLayer();
    loginLayer.style.display = "block";
};

As you can see, a getSingle function has been added. There is a concept of closure here. result variable will not be destroyed as long as it is referenced, which plays a role of cache. The parameter of the function is a function . If result is null or undefined , the subsequent logic will be executed, and the return value of the passed function, that is, the div, will be assigned to result . In this way, our following function only needs to be executed once. The next time it is called, result has a value, so it will be returned directly without executing the subsequent logic.

This concludes this article about the singleton pattern design pattern in JavaScript . For more information about the singleton pattern in JavaScript , please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JavaScript Design Patterns --- Detailed Explanation of Singleton Pattern [Four Basic Forms]
  • JS Design Pattern: A Brief Analysis of the Definition and Implementation of Singleton Pattern
  • JavaScript Design Patterns – Singleton Pattern Principles and Application Examples Analysis
  • Detailed explanation of the principle and usage of the singleton pattern in js design pattern
  • JS implements the encapsulation of data addition, deletion, modification and query functions based on the singleton pattern in the design pattern
  • JS Design Patterns: Singleton Pattern (I)
  • Understanding the Singleton Pattern in JavaScript Design Patterns

<<:  Solution to slow response of Tomcat server

>>:  Detailed explanation of the binlog log analysis tool for monitoring MySQL: Canal

Recommend

Method of dynamically loading geojson based on Vue+Openlayer

Load one or more features <template> <di...

Detailed explanation of the concept, principle and usage of MySQL triggers

This article uses examples to explain the concept...

HTML form tag usage learning tutorial

Forms in HTML can be used to collect various type...

How to configure Http, Https, WS, and WSS in Nginx

Written in front In today's Internet field, N...

Implementation of breakpoint resume in Node.js

Preface Normal business needs: upload pictures, E...

Description of the hr tag in various browsers

Generally, we rarely meet HR, but once we do, it c...

Html sample code for reading and displaying pictures in a local folder

One purpose Select a local folder on the Html pag...

Use of Zabbix Api in Linux shell environment

You can call it directly in the Linux shell envir...

Example of stars for CSS rating effect

What? What star coat? Well, let’s look at the pic...

A brief discussion on logic extraction and field display of Vue3 in projects

Table of contents Logical Layering Separate busin...

The difference between z-index: 0 and z-index: auto in CSS

I've been learning about stacking contexts re...

How to use async await elegantly in JS

Table of contents jQuery's $.ajax The beginni...

JavaScript to achieve JD.com flash sale effect

This article shares the specific code of JavaScri...