JavaScript设计模式之单例模式

  定义:保证一个类仅有一个实例,并且提供一个全局访问点。

   其实js实现单例相当简单,使用闭包隐藏私有变量,暴露一个访问点就ok了:

  

var Singleton = (function(){
     var instance = null;
    function getInstance(){
      if(!instance) instance = new Object();
      return instance;
    }
    return {
      getInstance: getInstance
    }
})();
var a = Singleton.getInstance();
var b = Singleton.getInstance();
a === b; //true

 

posted @ 2021-07-05 15:05  野鹤啊飞  阅读(26)  评论(0)    收藏  举报