Lazy singleton pattern

1. Singleton mode

There is one and only one instance in an environment and it is accessible to the current environment. At a small level, the current environment can be a function scope, block-level scope, and at a large level it can be a global Window or global environment. If singleton patterns are classified according to instance creation time, there are:

  • Normal singleton pattern: Created at the beginning of the environment
  • Lazy singleton pattern: created at a specific time

2. Lazy singleton pattern

From the definition of a singleton, where there is only one instance in an environment and it is created only when used, the current singleton can be called a lazy singleton

  • Lazy, which means that it is created only when it is used
  • Singleton means that there is only one instance of the current environment

Case study:

When the page opens, there is a login button, and when clicked, you need to create a DOM node.

(1) First, implement a function function: the function to create the node
var domFun = function () { var dom = document.createElement('div'); Dom.innerhtml = 'login window demo' dom.style.display = 'none'; document.body.appendChild(dom); return dom; }Copy the code

(2) Second, create functions that manage singletons

var createSingle = function (fn) { var result; return function () { return result || (result = fn.apply(this, arguments)); }}Copy the code

If the result variable already exists, return it. If it doesn’t, call the fn function and assign it to result. This procedure ensures that the current environment has only one instance.

(3) Mix functions that create nodes with functions that manage singletons

var createSingleDom = createSingle(domFun)
Copy the code

(4) Finally, when the button is clicked, the instance is created

var loginBtn = document.querySelector('.login')
loginBtn.onclick = function () {
    var loginDom = createSingleDom()
    console.log(loginDom)
    loginDom.style.display = 'block'
}
Copy the code

This process implements the lazy creation of nodes only when the login button is clicked.

Summary: The whole process, the process of creating lazy instances is decomposed, which is easier to modify and maintain. If, instead of creating div nodes, you create other content, such as image image, iframe nested web page, countdown, etc., you only need to replace the content in step (1).

Reference Book: JavaScript Design Patterns and Development Practices (Tseng)