简述
在JavaScript中,Singleton充当共享资源命名空间,从全局命名空间中隔离出代码实现,从而
为函数提供单一访问点。
如下实现一个Singleton
var mySingleton=(function(){
//实例保持了Singleton的引用
var instance;
function init(){
//Singleton
//私有方法和变量
function privateMethod(){
console.log("I am a private");
}
var privateVariable="I am also a private";
var privateRandomNumber=Math.random();
return{
//公有方法和变量
publicMethod:function(){
console.log("The public can see me");
},
publicProperty:"I am also a public",
getRandomNumber:function(){
return privateRandomNumber;
}
};
};
return{
//获取Singletond的实例,如果存在就返回,不存在就创建新实例
getInstance:function(){
if (!instance){
instance=init();
}
return instance;
}
};
})();
var myBadSingleton=(function(){
//实例保持了一个引用
var instance;
function init(){
//Singleton
var privateRandomNumber=Math.random();
return{
getRandomNumber:function(){
return privateRandomNumber;
}
};
};
return{
//每次都创建新实例
getInstance:function(){
instance=init();
return instance;
}
};
})();
var singleA=mySingleton.getInstance();
var singleB=mySingleton.getInstance();
console.log(singleA.getRandomNumber()===singleB.getRandomNumber());//true
var badSingletonA=myBadSingleton.getInstance();
var badSingletonB=myBadSingleton.getInstance();
console.log(badSingletonA.getRandomNumber!==badSingletonB.getRandomNumber);//ture