This is the third day of my participation in Gwen Challenge

preface

From the last article, we learned that design patterns and JavaScript object orientation are based on prototypes. If you are interested, you can go to learn about them. This article mainly introduces the implementation and application of singleton pattern in JavaScript.

What is the singleton pattern

First, let’s look at the definition of the singleton pattern

The singleton pattern, also known as the singleton pattern, specifies that a class has only one instance and provides globally accessible points of accessCopy the code

The singleton pattern has many applications in browsers, such as window objects, global cache, vuex, etc. This paper mainly introduces the design of several singleton patterns, which are simple singleton pattern, transparent singleton pattern, using proxy singleton pattern, and inert singleton pattern

Simple singleton pattern

Implementing a singleton is as simple as focusing on a single instance of a class at design time and providing global access points.

    const SingleModel = function(name) {
        this.name = name;
    }
    
    SingleModel.prototype.getName = function() {
        return this.name;
    }
    
    SingleModel.getInstance = (function() {
        let instance;
        return function(name) {
            if(! instance) { instance =new SingleModel(name);
            }
            return instance;
        }
    })()
    
    const a = SingleModel.getInstance('s1');
    const b = SingleModel.getInstance('s2');
    
    console.log(a === b); // true
Copy the code

As you can see, the above code uses the singleModel.getInstance method to get the instance, and they get the same instance, which is consistent with the singleton definition, so the above code is a basic singleton. One drawback is that we usually get the object instance through the new method. Here we need to use the exposed getInstance method to get the instance. This creates an opacity for the user, who must know that this is a singleton pattern and use getInstance to create the instance

Transparent singleton pattern

Singleton transparency presumably means that the user can create a unique instance using the new operator without calling getInstance to create the instance. Knowing the flaws in the code above, let’s go ahead and make instance creation “transparent”

    const SingleModel = (function() {
        let instance;
        function Init(name) {
            if(! instance) {this.name = name;
                instance = this;
            }
            return instance;
        }
        Init.prototype.getName = function() {
            return this.name
        }
        return Init
    })()
    
    const a = new SingleModel('s1');
    const b = new SingleModel('s2');
    
    console.log(a === b); // true
Copy the code

At this point, we can now create singletons using the new operator. As you can see from the code, SingleModel is a function that is returned by a function that executes immediately. When instantiated, we actually call Init. Although we implemented the singleton creation pattern with the New service, the use of anonymous functions and closures during the creation process made the class creation a bit strange. If we can create a normal class to implement the singleton, so much the better

The proxy implements the singleton pattern

To implement a singleton using a normal class, it is not possible to declare it directly. We can do this by proxy, that is, implementing a normal class and creating a singleton using a proxy function. The code is as follows:

    const SingleModel = function(name) {
        this.name = name;
    }
    
    SingleModel.prototype.getName = function() {
        return this.name;
    }
    
    const createModelProxy = (function() {
        let instance;
        return function(name) {
            if(! instance) { instance =new SingleModel(name);
            }
            return instance;
        }
    })()
    
    const a = new createModelProxy('s1');
    const b = new createModelProxy('s2');
    
    console.log(a === b); // true
Copy the code

The implementation is simple: separate the method for creating a singleton and place it in a proxy method. In this way, the creation singleton method is separate from the ordinary class.

Inert singleton

Lazy singletons are created when they need to be used, whereas normal singletons are called by classes and declarations at load time. In JavaScript, the lazy singleton approach is often used. For example, in the design login, there will be a popup window to enter the account password, and when the user clicks login, this window will pop up. If you use an inert singleton, it will trigger the event to create a pop-up window and render it to the page only when you click on the login window.

summary

This article mainly introduces the concept of singleton pattern: a class has only one instance, and provides global access point introduces several ways to create a singleton pattern, as well as introduces the lazy singleton and ordinary singleton.

If you find this article helpful, you can encourage the author by clicking a “like”, and if you want to learn more about JavaScript or Node, you can click here. Please point out any inaccuracies or errors in the comments section.

reference

  1. JavaScript design patterns and development practices