English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Instance Sharing of Singleton Pattern Implementation in JavaScript

Traditional Singleton Pattern

Ensure that a class has only one instance and provide a global access point to it.

The core idea of implementing singleton

It is just to use a variable to mark whether an object has been created for a class, if so, return the previously created object directly when obtaining the instance of the class next time. Next, we will强行 implement this idea with JavaScript, please see the code below:

var Singleton = function(name) {
  this.name = name;
};
Singleton.prototype.getName = function() {   alert(this.name);
};
Singleton.getInstance = (function() {   var instance = null;
  return function(name) {
          if (!instance) {
            instance = new Singleton(name);
          };
        return instance;       }
})();

We obtain the unique object of the Singleton class through Singleton.getInstance, which is indeed correct, but JavaScript itself does not have the concept of class, so our forced implementation of the traditional singleton idea is meaningless at all. Such code is both stinky and long (actually, it's not comfortable for me to look at it, hahaha). Next, we will use JavaScript closure to implement a singleton, please see the code below:

var CreateDiv = (function() {       var instance;
      var CreateDiv = function(html) {           if (instance) {
            return instance;           }
          this.html = html; this.init();
          return instance = this;
};
CreateDiv.prototype.init = function() {
var div = document.createElement('div');
div.innerHTML = this.html; 
document.body.appendChild(div);
      };
      return CreateDiv; })();
var a = new CreateDiv('sven');1'); var b = new CreateDiv('sven');2');
alert(a === b); // true

It can be seen that we indeed use closure to implement a singleton, but this code is still highly coupled. The constructor function of CreateDiv is actually responsible for two things. First, it is responsible for creating the object and executing the init method, and second, it ensures that only one object is present. Such code is not clear in terms of responsibility. Now we need to separate these two tasks. The constructor is responsible for building the object, and the judgment of whether to return an existing object or to construct a new one and return it is left to another function to complete. In fact, it is also to satisfy a programming philosophy: the Single Responsibility Principle. Such code can better decouple. Please see the following code:

var CreateDiv = function (html) {
    this.html = html;
    this.init();
  };
  CreateDiv.prototype.init = function () {
    var div = document.createElement('div');
    div.innerHTML = this.html;
    document.body.appendChild(div);
  };
  var ProxySingletonCreateDiv = (function () {
    var instance;
    return function (html) {
      if (!instance) {
        instance = new CreateDiv(html);
      };
      return instance;
    };
  })();
  var a = new ProxySingletonCreateDiv('sven');1');
  var b = new ProxySingletonCreateDiv('sven');2');
  alert(a === b); //true

It can be seen that currently, our constructor function CreateDiv is only responsible for constructing objects. Whether to return an existing object or to construct a new object and return it is left to the proxy class proxySingletonCreateDiv to handle, which makes the code look more comfortable (zhuang) and satisfying (bi)!

Finally, attach a highly abstract singleton pattern code, the essence of lazy singleton!

//Singleton pattern abstraction, separates the function of creating objects and the judgment of whether the object has been created
  var getSingle = function (fn) {
    var result;
    return function () {
      return result || (result = fn.apply(this, arguments));
    };
  };

The parameter fn is our constructor function. As long as we pass any constructor function we need, we can generate a new lazy singleton. For example, by passing a constructor function to create a girlfriend, and calling getSingle(), a new girlfriend can be generated. If getSingle() is called again later, it will only return the girlfriend created just now. As for the new girlfriend - she does not exist.

Common Use Cases of Singleton

You can use the singleton idea to implement it when you need to generate a unique object, such as the page login box, which is only possible to have one login box. Of course, you can also implement it without the singleton idea, but the result may be that you need to generate and display a new login box each time you want to display the login box (consumes performance), or accidentally display two login boxes.

That's all the learning experience we share with you about implementing singleton mode in JS. Thank you for your support of the Yell Tutorial.

Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, does not undergo manual editing, and does not assume relevant legal liabilities. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email for reporting, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)

You May Also Like