JavaScript uses proxy to implement singleton mode

var CreateDiv = function(html){
   this.html = html;
   this.init();
};

CreateDiv.prototype = 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 ProxySingleCreateDiv( 'a' );
var b = new ProxySingleCreateDiv( 'b' );

alert(a === b); //true

The singleton mode implemented by the proxy above transfers the logic responsible for managing the singleton to the proxy class ProxySingleTonCreateDiv, and CreateDiv becomes an ordinary class, combined with ProxySingleTonCreateDiv to realize the singleton mode.

Guess you like

Origin blog.csdn.net/joyksk/article/details/79760898