Design Patterns - Implementing Singleton Patterns with JavaScript

Learning Notes of JavaScript Design Patterns and Development Practice
Design Patterns - Implementing Singleton Patterns with JavaScript

Explain

Definition: Ensure that a class has only one instance and provide a global access point to access it.
Use scenarios: global caching, Windows objects, login floating windows, etc.
Key: Use a variable to indicate whether an object has been created for a class, if not, to return it.

Standard Singleton Model

Code implementation:
javascript code

/**
 * Standard Singleton Model
 * The disadvantage is that the user must know that this is a singleton class, which could have been directly new xxx, and now becomes xxx.getInstance
 */
var Singleton = function (name) {
  this.name = name
  this.instance = null
};
Singleton.prototype.getName = function () {
  alert(this.name)
}
Singleton.prototype.getInstance = function (name) {
  if(this.instance!==null){
    this.instance = new Singleton(name)
  }
  return this.instance
}

Transparent singleton mode

javascript code

/**
 * Using Closure and IIFE to Realize Transparent Singleton Mode
 * But it violates the principle of single duty.
 * The disadvantage is that when a singleton is no longer needed, the constructor needs to be overwritten
 */
var CreateDiv = (function() {
  var instance
  var CreateDiv = function(html) {
    if (instance) {
      return instance
    }
    this.html = html
    this.init() // Execute init method
    return (instance = this) // Guarantee that there is only one object
  }
  CreateDiv.prototype.init = function() {
    var div = document.createElement('div')
    div.innerHTML = this.html
    document.body.appendChild(div)
  }
  return CreateDiv
})()

Singleton implemented by proxy

javascript code

/**
 * Agent Implementation Singleton
 * Move the logic responsible for managing singletons to proxy Singleton Create
 */
var CreateSpan = function(html) {
  this.html = html
  this.init()
}
CreateSpan.prototype.init = function() {
  var span = document.createElement('span')
  span.innerHTML = this.html
  document.body.appendChild(span)
}

var proxySingletonCreate = (function() {
  var instance
  return function(html) {
    if (!instance) [(instance = new CreateSpan('test'))]
    return instance
  }
})()

A General Method for Creating Singletons

As can be seen from the above, the core of creating a singleton is to use a variable to indicate whether the object was created, that is:
javascript code

var instance
if(!instance) {
   instance = xxx
}

Specific code implementation is:
javascript code

/**
 * An abstract method for creating singletons
 * @param {function} fn 
 */
var getSingle = function(fn) {
  var result
  return function() {
    return result || (result = fn.apply(this, arguments)) 
  }
}

Keywords: Javascript Windows

Added by Thumper on Wed, 02 Oct 2019 11:56:39 +0300