Singleton pattern: Ensure that a class has only one instance and provide a global access point to access it

Implement the singleton pattern with a proxy

Application Scenarios:

Use the CreateDiv singleton class, which is responsible for creating a unique DIV node on the page

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( 'sven1' ); 
var b = new ProxySingletonCreateDiv( 'sven2' );
alert( a === b );  //true
Copy the code

Inert singleton

This refers to the creation of object instances only when needed. Lazy singletons are the focus of the singleton pattern

Application Scenarios:

Create a unique floating window

var getSingle = function( fn ){
   var result;
   return function() {returnresult || ( result = fn .apply(this, arguments ) ); }}; var createLoginLayer =function(){

    var div = document.createElement( 'div' );
    div.innerHTML = 'I'm logging in to the floating window.';
    div.style.display = 'none';  
    document.body.appendChild( div );

    return div;
};
var createSingleLoginLayer = getSingle( createLoginLayer );
document.getElementById( 'loginBtn' ).onclick = function(){ 
    var loginLayer = createSingleLoginLayer(); 
    loginLayer.style.display = 'block';
};
Copy the code

Series of articles:

JavaScript Design Patterns and Development Practices