javascript 設計模式之單體(Singleton)模式

單體模式介紹

    單體模式最初的定義出現於《設計模式》(艾迪生維斯理, 1994):「保證一個類僅有一個實例,並提供一個訪問它的全局訪問點。」 javascript

         javascript是一個沒有類的程序語言,固然也能夠去模擬面嚮對象語言的類式寫法。對於javascript咱們廣義的去理解單體模式。

      javascript的單體模式能夠帶來哪些做用那?首先確定是減小了全局變量數目,javascript的全局變量是該語言的糟糕特性之一,做爲一個優秀的JS程序員必定要控制全局變量的使用。其次咱們把一組相關的邏輯單元組織在一個單體中,用來劃分命名空間,這樣使得代碼可讀性更強更好維護。 java

    下面咱們學習javascript的單體模式,咱們以瀏覽器類型和版本爲模型進行實例。 程序員

單體模式示例

簡單的單體模式

最簡單的單體模式實現,使用{}將相關屬性方法組織起來。 設計模式

var Browser = {
type : 'Firefox',
version : '3.6',
getType : function(){return this.type;},
getVersion : function(){return this.version;}
};
console.log(Browser.getType());
console.log(Browser.getVersion());
console.log(Browser.type);

咱們已經實現了最簡單是單體模式,可是此時的單體模式很脆弱,若是有人寫下以下的代碼,那麼咱們的單體就被破壞了。 瀏覽器

var Browser = {
type : 'Firefox',
version : '3.6',
getType : function(){return this.type;},
getVersion : function(){return this.version;}
};
console.log(Browser.getType());
console.log(Browser.getVersion());
Browser.type = 'change';
console.log(Browser.getType());
console.log(Browser.getVersion());


此時的輸出內容在的類型已經被改變掉了。咱們的瀏覽器類型能夠隨意改變,這顯然不行的了。咱們須要使用私有成員來進行這個單體模式的變形。那麼咱們能夠使用閉包來完成私有成員的處理。 閉包

使用閉包的單體模式

var Browser = (function(){
  var type = 'Firefox';
  var version = '3.6';
  function _getType(){return type;}
  function _getVersion(){return version;}
  return {
     getType:function(){return _getType();},
     getVersion:function(){return _getVersion();}
  }
})();
console.log(Browser.getType());
console.log(Browser.getVersion());  console.log(Browser.type);


此時外面已經訪問不到 Browser內部的類型與版本。下面咱們繼續升級,此次咱們升級到只有使用的時候纔去實例化Browser。 學習

惰性實例化單體模式

var Browser = (function(){
  var uniqueInstane;
  function constructor(){
      var type = 'Firefox';
      var version = '3.6';
      function _getType(){return type;}
      function _getVersion(){return version;}
      return {
         getType:function(){return _getType();},
         getVersion:function(){return _getVersion();}
      }
  }
  return {
      getInstance : function(){
        if(!uniqueInstane){
           console.log('instance init.');
           uniqueInstane = constructor();
        }
        return uniqueInstane;
      }
  }
})();
console.log(Browser.getInstance().getType());
console.log(Browser.getInstance().getVersion());

此時咱們此次的單體模式的示例就算是完畢了。 this

單體模式總結

    上面咱們示例了幾種關於瀏覽器的單體模式示例。單體模式的好處在於對代碼的組織,很是便於維護。結合閉包能夠更好的對私有成員的操做。單體模式的弊端在於提供的是一種單點訪問,可能致使模塊間的強耦合。在選擇這種模式的時候應該考慮到這種狀況。最適合纔是最好的。 spa

相關文章
相關標籤/搜索