欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

js單例模式詳解實例

 更新時間:2013年11月21日 10:28:07   作者:  
這篇文章主要介紹了什么是單例單例模式、使用場景,提供了3個示例給大家參考

什么是單例?

單例要求一個類有且只有一個實例,提供一個全局的訪問點。因此它要繞過常規(guī)的控制器,使其只能有一個實例,供使用者使用,而使用著不關(guān)心有幾個實例,因此這是設(shè)計者的責(zé)任

復(fù)制代碼 代碼如下:

In JavaScript, Singletons serve as a shared resource namespace which isolate implementation code from the global namespace so as to provide a single point of access for functions.

在javascript中,單例被當(dāng)做一個全局的命名空間,提供一個訪問該對象的一個點。

使用場景

復(fù)制代碼 代碼如下:

In practice, the Singleton pattern is useful when exactly one object is needed to coordinate others across a system.

單例比較適用于一個對象和其他系統(tǒng)進行交互。

類比

單例有點類似于一個小組的小組長,在一段時間內(nèi)只有一個小組長,有小組長來指定組員的工作,分配和協(xié)調(diào)和組員的工作。

實例1:這個是最簡單的單例,通過key,value的形式存儲屬性和方法

復(fù)制代碼 代碼如下:

var A = {
   xx:3,
   yy:4,
   B:function(el){

   },
   C:function(el){

   },
   D:function(el){

   },
   E:function(el){

   }
}


實例2:首先創(chuàng)建一個實例的引用,然后判斷這個實例是否存在,如果不存在那么就創(chuàng)建,存在的話,就直接返回,保證有且只有一個。

復(fù)制代碼 代碼如下:

var mySingleton = (function () {

// Instance 存儲一個單例實例的引用
var instance;

function init() {

// Singleton

// 私有的方法和變量
function privateMethod(){
    console.log( "I am private" );
}

var privateVariable = "Im also private";

return {

  // 共有的方法和變量
  publicMethod: function () {
    console.log( "The public can see me!" );
  },

  publicProperty: "I am also public"
};

};

return {

// 如果實例不存在,那么創(chuàng)建一個
getInstance: function () {

  if ( !instance ) {
    instance = init();
  }

  return instance;
}

};

})();

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

實例3:

復(fù)制代碼 代碼如下:

var SingletonTester = (function () {
  // options: an object containing configuration options for the singleton
  // e.g var options = { name: "test", pointX: 5};
  function Singleton( options )  {
    // set options to the options supplied
    // or an empty object if none are provided
    options = options || {};
    // set some properties for our singleton
    this.name = "SingletonTester";
    this.pointX = options.pointX || 6;
    this.pointY = options.pointY || ;
  }
  // our instance holder
  var instance;
  // an emulation of static variables and methods
  var _static  = { 
    name:  "SingletonTester",
    // Method for getting an instance. It returns
    // a singleton instance of a singleton object
    getInstance:  function( options ) {  
      if( instance  ===  undefined )  {   
        instance = new Singleton( options );  
      }  
        return  instance;     
    }
  };
  return  _static;
})();
var singletonTest  =  SingletonTester.getInstance({
  pointX:  5
});
// Log the output of pointX just to verify it is correct
// Outputs: 5
console.log( singletonTest.pointX );

相關(guān)文章

最新評論