您好,欢迎访问一九零五行业门户网

js单例模式详解实例_基础知识

什么是单例?
单例要求一个类有且只有一个实例,提供一个全局的访问点。因此它要绕过常规的控制器,使其只能有一个实例,供使用者使用,而使用着不关心有几个实例,因此这是设计者的责任
复制代码 代码如下:
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 );
其它类似信息

推荐信息