Singleton 模式

簡述

在JavaScript中,Singleton充當共享資源命名空間,從全局命名空間中隔離出代碼實現,從而
爲函數提供單一訪問點。javascript

以下實現一個Singleton

var mySingleton=(function(){
  //實例保持了Singleton的引用
  var instance;
  function init(){
    //Singleton
    //私有方法和變量
    function privateMethod(){
        console.log("I am a private");
    }
    var privateVariable="I am also a private";
    var privateRandomNumber=Math.random();
    return{
      //公有方法和變量
      publicMethod:function(){
        console.log("The public can see me");
      },
      publicProperty:"I am also a public",
      getRandomNumber:function(){
        return privateRandomNumber;
      }
    };
  };
  return{
    //獲取Singletond的實例,若是存在就返回,不存在就建立新實例
    getInstance:function(){
      if (!instance){
        instance=init();
      }
      return instance;
    }
  };
})();

  var myBadSingleton=(function(){
  //實例保持了一個引用
  var instance;
  function init(){
    //Singleton
    var privateRandomNumber=Math.random();
    return{
      getRandomNumber:function(){
        return privateRandomNumber;
      }
    };
  };
  return{
    //每次都建立新實例
    getInstance:function(){
      instance=init();
      return instance;
    }
  };
})();

  var singleA=mySingleton.getInstance();
  var singleB=mySingleton.getInstance();
  console.log(singleA.getRandomNumber()===singleB.getRandomNumber());//true

  var badSingletonA=myBadSingleton.getInstance();
  var badSingletonB=myBadSingleton.getInstance();
  console.log(badSingletonA.getRandomNumber!==badSingletonB.getRandomNumber);//ture
相關文章
相關標籤/搜索