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

Web developers are concerned about the coexistence of IE7 and IE8

I installed IE8 today. When I went to the Microso...

MySQL merges multiple rows of data based on the group_concat() function

A very useful function group_concat(), the manual...

Detailed steps for remote deployment of MySQL database on Linux

Linux remote deployment of MySQL database, for yo...

How to use nginx to configure access to wgcloud

The nginx configuration is as follows: Such as ht...

Docker port mapping and external inaccessibility issues

The Docker container provides services and listen...

Solution to input cursor misalignment in Chrome, Firefox, and IE

Detailed explanation of the misplacement of the in...

MySQL 8.0.21 installation tutorial with pictures and text

1. Download the download link Click download. You...

Summary of MySQL injection bypass filtering techniques

First, let’s look at the GIF operation: Case 1: S...

Analysis of MySQL general query log and slow query log

The logs in MySQL include: error log, binary log,...

How to install Maven automatically in Linux continuous integration

Unzip the Maven package tar xf apache-maven-3.5.4...

The difference between where and on in MySQL and when to use them

When I was writing join table queries before, I a...

Do you know the difference between empty value and null value in mysql

Preface Recently I found that my friend's met...