標籤:
一、什麼是單例
意思是指擷取的對象只有一份。
二、最通用的單例
任何時刻擷取SingLeton.instance都是同一個對象
1 var SingLeton={2 instance:{3 property:1,4 getProperty:function(){return this.property;}5 } 6 }
三、轉變成通過函數的方法來擷取對象
類似於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;}
至此單例出來了,可以驗證下
JavaScript單例模式