JavaScript单例模式

时间:2023-03-08 18:52:36

一、什么是单例

  意思是指获取的对象只有一份。

二、最通用的单例 

任何时刻获取SingLeton.instance都是同一个对象

  var SingLeton={
instance:{
property:1,
getProperty:function(){return this.property;}
}
}

三、转变成通过函数的方法来获取对象

类似于SingLeton()(),但是问题来了,每次执行都会重新创建instance对象,如果已经存在那么无需再创建

var Singleton=function(){
var instance={
property:1,
getProperty:function(){return this.property;}
}; var getInstance=function(){
return instance;
}
return getInstance; }
console.log(Singleton()());
var Singleton=function(){
var instance=null;
function createInstance(){
return {
property:1,
getProperty:function(){return this.property;}
};
} var getInstance=function(){
instance=instance||createInstance();
return instance;
}
return getInstance; }
console.log(Singleton()());

问题又来了,怎么不像其他语言那样,通过SingLeton.getInstance()来获取对象呢

四、自调用函数

要想改造成SingLeton.getInstance(),那SingLeton必须一出来就是一个对象,该对象包含一个方法,可以返回instance对象,我们想到采用让函数立即执行的方式


var Singleton=(function(){
var instance=null;
function createInstance(){
console.log("create");
return {
property:1,
getProperty:function(){return this.property;}
};
}
return {
getInstance:function(){
instance=instance||createInstance();
return instance;
}
} })()
console.log(Singleton.getInstance());
console.log(Singleton.getInstance());

//result:
create 
Object {property: 1}getProperty: (){return this.property;}

Object {property: 1}getProperty: (){return this.property;}
 

至此单例出来了,可以验证下