** Definition: ** guarantees that a class has only one instance and provides a global access point to access it.
Singleton pattern is a common design pattern, some objects often we only need one, use scenarios such as shopping cart, global cache, etc
For example, we’ll use the CreateDiv singleton class, which is responsible for creating a unique DIV node on the page
Var CreateDiv = function(HTML){if (instance){// Return instance} this.html = HTML this.init() return instance = this // Create instance for the first time, Init = function(){var div = document.createElement('div') div.innerhtml = this.html document.body.appendChild( div ) } return CreateDiv })() var a = new CreateDiv( 'ele1' ) var b = new CreateDiv( 'ele2' ) alert ( a === b ) // trueCopy the code
If we only need a “unique” object, why create a “class” for it in the first place? In javasript, it is very easy to create a global object, just var obj = {}, so why use the singleton pattern? First, the global variable is not a singleton pattern, declare obj is a global object, but it does not exist “unique”, because as the project grows, If there are many of these global variables, it is easy to pollute the namespace, which can be painful to maintain later. Now that you’ve written a singleton, the singleton code doesn’t make much sense.
Scene: In a web project of an online shopping platform, we choose goods and add them to the shopping cart. When we select the goods and click the shopping cart icon, the shopping cart pop-up window opens.
The general idea is to create the shopping cart popup when loading, then hide it, and click the icon to show it again; But loading this popover would be a bit wasteful if we were just browsing through items without planning to buy them. So here you can use the lazy singleton pattern.
var createLoginLayer = (function(){ var div return function(){ if ( ! Div){div = document.createElement('div') div.innerhtml = 'shopping cart popup' div.style.display = 'none' document.body.appendChild( div ) } return div } })() document.getElementById( 'loginBtn' ).onclick = function(){ var loginLayer = createLoginLayer() loginLayer.style.display = 'block' }Copy the code
** Summary: the ** singleton pattern is a simple but very practical pattern, especially the lazy singleton technique, where objects are created when appropriate and only one is created. Lazy singletons can avoid object loss or overwriting, and lazy object creation can avoid resource waste.