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

Page Refactoring Skills - Javascript, CSS

About JS, CSS CSS: Stylesheet at the top Avoid CS...

Hidden overhead of Unix/Linux forks

Table of contents 1. The origin of fork 2. Early ...

Detailed explanation of the use of filter properties in CSS

The filter attribute defines the visual effect of...

Detailed steps to expand LVM disk in Linux

1. Add a hard disk 2. Check the partition status:...

Implementation steps for building FastDFS file server in Linux

Table of contents 1. Software Package 2. Install ...

The combination and difference between ENTRYPOINT and CMD in dockerfile

In the previous article [Detailed explanation of ...

Implementation of nginx worker process loop

After the worker process is started, it will firs...

Tutorial diagram of installing centos7.3 on vmware virtual machine

VMware Preparation CentOS preparation, here is Ce...

This article will show you what Vite does to the browser's request

Table of contents Working principle: What does th...

Vite+Electron to quickly build VUE3 desktop applications

Table of contents 1. Introduction 2. Create a Vit...

Detailed explanation of four solutions to floating problems in CSS layout

1. Cause: The effect after the subbox is set to f...

Linux automatically deletes logs and example commands from n days ago

1. Delete file command: find the corresponding di...

Issues with upgrading Python and installing Mongodb drivers under Centos

Check the Python version python -V If it is below...