js 设计模式-单例模式

本文参考:http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavascript

目录:

  1)什么是单例

  2)使用场景

  3)类比

  3)举例

什么是单例?

  单例要求一个类有且只有一个实例,提供一个全局的访问点。因此它要绕过常规的控制器,使其只能有一个实例,供使用者使用,而使用着不关心有几个实例,因此这是设计者的责任

  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中,单例被当做一个全局的命名空间,提供一个访问该对象的一个点。

使用场景

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

  单例比较适用于一个对象和其他系统进行交互。

类比

  单例有点类似于一个小组的小组长,在一段时间内只有一个小组长,有小组长来指定组员的工作,分配和协调和组员的工作。

举例

实例1:这个是最简单的单例,通过key,value的形式存储属性和方法

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

   },
   C:function(el){
   
   },
   D:function(el){
   
   },
   E:function(el){
   
   }
}

  

实例2:首先创建一个实例的引用,然后判断这个实例是否存在,如果不存在那么就创建,存在的话,就直接返回,保证有且只有一个。  

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 {

// 如果实例不存在,那么创建一个
getInstance: function () {

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

  return instance;
}

};

})();

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

实例3:

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 ); 

欢迎大家拍砖!!

 

  

  

posted @ 2012-09-06 16:15  yupeng  阅读(2754)  评论(0编辑  收藏  举报