javascript单例模式

      单例模式的定义:保证一个类只有一个实例,并提供一个访问它的全局访问点。

      单例模式是一种常用的设计模式,有些对象我们只需要一个,比如线程池、全局缓存、浏览器中的window对象等。在JavaScript中,单例模式同样应用广泛。

      例如下面的代码负责在页面中创建唯一的div:

            var CreateDiv = (function(){

                  var instance;

                  var CreateDic = function(html){

                        if(instance){

                              return instance;

                        }  

                        this.html = html;

                        this.init();

                        return instance = this;

                   }

                   CreateDiv.prototype.init = function(){

                         var div = document.createElement("div");

                         div.innerHTML = this.html;

                         document.body.appendChild(div);

                   }

                   return CreateDiv;

             })();

            

             var a = new CreateDiv("one");

             var a = new CreateDiv("two");

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

      下面的代码是对上面的改良,这样可以将CreateDiv的构造函数与控制创建唯一对象的代码分离、解耦:

            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 proxySingleton = (function(){

                   var instance;

                   return function(html){

                         if(!instance){

                                instance = new CreateDiv(html);

                         }

                         return instance;

                   };

             })();

            var a = new proxySingleton("one");

            var b = new proxySingleton("two");

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

      

      上面是单例模式在JavaScript语言中的具体运用,其实还可以更进一步地将创建单例的代码抽象:

            var getSingle = function(fn){

                  var result;

                  return function(){

                        return result || ( result = fn.apply(this, arguments) );

                  };

            }

      这样一来,上面的第一个例子就可以改成下面这样了:

           var proxySingleton = getSingle (new CreateDiv(html));

           proxySingleton();

原文地址:https://www.cnblogs.com/xbj-2016/p/5802988.html