How to implement the singleton pattern in Javascript

How to implement the singleton pattern in Javascript

Overview

The singleton pattern is also called the monomer pattern, which stipulates that a class has only one instance and provides a global access point;

Before reading this article, you may feel vague or unclear about the concept of singleton pattern, but in fact, you must have used singleton pattern in daily development;

There is no class definition in JavaScript. The characteristics of the singleton pattern are "unique" and "global access", so we can think of the global object in JavaScript. The feature of ES6's let that does not allow repeated declarations just meets these two characteristics; yes, the global object is the simplest singleton pattern;

let obj = {
    name:"Salted Fish",
    getName:function(){}
}

From the above code, we can know that obj is a singleton, because obj just meets the two characteristics of the singleton pattern: "unique" and "globally accessible";

However, we do not recommend implementing singletons this way, because global objects/global variables have some disadvantages:

Pollutes the namespace (variable name conflicts are easy) and is not easy to control during maintenance (if you are not careful, it will be directly overwritten)

Code Implementation

Simple version of singleton pattern

Analysis: There can only be one instance, so we need to use an if branch to judge. If it already exists, return directly. If it does not exist, create a new instance.

let Singleton = function(name){
    this.name = name;
    this.instance = null; 
}

Singleton.prototype.getName = function(){
    console.log(this.name);
}

Singleton.getInstance = function(name){
    if (this.instace) {
        return this.instance; 
    }
    return this.instance = new Singleton(name);
}

let winner = Singleton.getInstance("winner"); //winner
console.log(winner.getName());
let sunner = Singleton.getInstance("sunner"); //winner
console.log(sunner.getName())

In the above code, we use the value of a variable instance to determine whether an instance already exists. If it does, we directly return this.instance. If it does not exist, we create a new instance and assign it to instance.

However, there are still problems with the above code, because the operation of creating an object and the operation of judging the instance are coupled together, which does not conform to the "single responsibility principle";

Improved version

Idea: Use a closure to implement the operation of judging the instance;

Closure warning: Students who don't understand closures should learn closures first

let CreateSingleton = (function(){
    let instance = null;
    return function(name){
        this.name = name;
        if(instance){
            return instance
        }
        return instance = this;
    }
})()


CreateSingleton.prototype.getName = function(){
        console.log(this.name);
}

let winner = new CreateSingleton("winner"); //winner
console.log(winner.getName());
let sunner = new CreateSingleton("sunner"); //winner
console.log(sunner.getName())

Proxy version singleton mode

Through the form of proxy, the operation of creating objects and the operation of instance judgment are decoupled and split to achieve a smaller granularity division, which complies with the "single responsibility principle";

let ProxyCreateSingleton = (function(){
    let instance = null;
    return function(name){
        if(instance){
            return instance
        }
        return instance = new Singlton(name);
    }
})();

let Singlton = function(name){
    this.name = name;
} 

Singlton.prototype.getName = function(){
    console.log(this.name);
}

let winner = new ProxyCreateSingleton("winner");
console.log(winner.getName());
let sunner = new ProxyCreateSingleton("sunner");
console.log(sunner.getName());

In the above code, ProxyCreateSingleton() is only responsible for judging the instance, and Singlton is only responsible for creating objects and assigning values;

Lazy Singleton Pattern

We often encounter such a scenario: a page is called multiple times and there are pop-up prompts, but the prompt content is different;

At this time, we can immediately think of the singleton mode. The pop-up window is a singleton instance, and the prompt content is parameter passing. We can use the lazy singleton mode to implement it.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div id="loginBtn">Salted fish with dreams</div>
</body>
<script>
let getSingleton = function(fn) {
    var result;
    return function() {
        return result || (result = fn.apply(this, arguments)); // Determine this context and pass parameters}
}
let createAlertMessage = function(html) {
    var div = document.createElement('div');
    div.innerHTML = html;
    div.style.display = 'none';
    document.body.appendChild(div);
    return div;
}

let createSingleAlertMessage = getSingleton(createAlertMessage);
    document.getElementById('loginBtn').onclick=function(){
        let alertMessage = createSingleAlertMessage('It seems like a real idiot');
        alertMessage.style.display = 'block';
    }
</script>
</html>

Lazy singleton means that our instance is not created when the page starts loading. The instance is created only after we click on the div of the page (created on demand), which can improve the performance of our web pages and speed up our page rendering.

The above is the details of how to implement the singleton pattern with Javascript. For more information about the Javascript singleton pattern, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Singleton design pattern in JavaScript
  • Implementing singleton mode based on JavaScript
  • Detailed explanation of the principle and usage of the singleton pattern in js design pattern
  • JS Design Patterns: Singleton Pattern (I)
  • A brief description of the singleton pattern in js design pattern

<<:  19 MySQL optimization methods in database management

>>:  Detailed explanation of Linux text editor Vim

Recommend

Why is your like statement not indexed?

Preface This article aims to explain the most bor...

CSS new feature contain controls page redrawing and rearrangement issues

Before introducing the new CSS property contain, ...

Detailed steps to use Redis in Docker

1. Introduction This article will show you how to...

How to upgrade CentOS7 to CentOS8 (detailed steps)

This article uses a specific example to introduce...

MySQL 8.0.15 download and installation detailed tutorial is a must for novices!

This article records the specific steps for downl...

Explanation of the steps for Tomcat to support https access

How to make tomcat support https access step: (1)...

Teach you step by step to develop a brick-breaking game with vue3

Preface I wrote a few examples using vue3, and I ...

Navicat for MySQL scheduled database backup and data recovery details

Database modification or deletion operations may ...

Summary of using the exclamation mark command (!) in Linux

Preface Recently, our company has configured mbp,...

Detailed description of the function of new in JS

Table of contents 1. Example 2. Create 100 soldie...

How to transfer files between Docker container and local machine

To transfer files between the host and the contai...

Explanation of factors affecting database performance in MySQL

A story about database performance During the int...

Teach you how to build a react+antd project from scratch

The previous articles were all my own learning lo...