單例模式的定義:保證一個(gè)類僅有一個(gè)實(shí)例,并提供一個(gè)全局訪問他的訪問點(diǎn)。
那么問題來了勤庐,我們?nèi)绾伪WC一個(gè)類僅有一個(gè)實(shí)例呢,實(shí)現(xiàn)的方法一般是先判斷實(shí)例存在與否好港,如果存在直接返回愉镰,如果不存在就創(chuàng)建了再返回,這就確保了一個(gè)類只有一個(gè)實(shí)例對(duì)象钧汹。在JavaScript里丈探,單例作為一個(gè)命名空間提供者,從全局命名空間里提供一個(gè)唯一的訪問點(diǎn)來訪問該對(duì)象拔莱。
在JavaScript里碗降,實(shí)現(xiàn)單例的方式有很多種,其中最簡(jiǎn)單的一個(gè)方式是使用對(duì)象字面量的方法塘秦,其字面量里可以包含大量的屬性和方法:
varmySingleton = {
property1: "something",
property2: "something else",
method1:function() {
console.log('hello world');
}
};
如果以后要擴(kuò)展該對(duì)象讼渊,你可以添加自己的私有成員和方法,然后使用閉包在其內(nèi)部封裝這些變量和函數(shù)聲明尊剔。只暴露你想暴露的public成員和方法爪幻,樣例代碼如下:
varmySingleton =function() {
/* 這里聲明私有變量和方法 */
varprivateVariable = 'something private';
functionshowPrivate() {
console.log(privateVariable);
}
/* 公有變量和方法(可以訪問私有變量和方法) */
return{
publicMethod:function() {
showPrivate();
},
publicVar: 'the public can see this!'
};
};
varsingle = mySingleton();
single.publicMethod();// 輸出 'something private'console.log(single.publicVar);// 輸出 'the public can see this!'
上面的代碼很不錯(cuò)了,但如果我們想做到只有在使用的時(shí)候才初始化须误,那該如何做呢挨稿?為了節(jié)約資源的目的,我們可以另外一個(gè)構(gòu)造函數(shù)里來初始化這些代碼京痢,如下:
varSingleton = (function() {
varinstantiated;
functioninit() {
/*這里定義單例代碼*/
return{
publicMethod:function() {
console.log('hello world');
},
publicProperty: 'test'
};
}
return{
getInstance:function() {
if(!instantiated) {
instantiated = init();
}
returninstantiated;
}
};
})();
/*調(diào)用公有的方法來獲取實(shí)例:*/
Singleton.getInstance().publicMethod();
知道了單例如何實(shí)現(xiàn)了奶甘,但單例用在什么樣的場(chǎng)景比較好呢?其實(shí)單例一般是用在系統(tǒng)間各種模式的通信協(xié)調(diào)上历造,下面的代碼是一個(gè)單例的最佳實(shí)踐:
varSingletonTester = (function() {
//參數(shù):傳遞給單例的一個(gè)參數(shù)集合functionSingleton(args) {
//設(shè)置args變量為接收的參數(shù)或者為空(如果沒有提供的話)varargs = args || {};
//設(shè)置name參數(shù)this.name = 'SingletonTester';
//設(shè)置pointX的值this.pointX = args.pointX || 6;//從接收的參數(shù)里獲取甩十,或者設(shè)置為默認(rèn)值//設(shè)置pointY的值this.pointY = args.pointY || 10;
}
//實(shí)例容器varinstance;
var_static = {
name: 'SingletonTester',
//獲取實(shí)例的方法//返回Singleton的實(shí)例getInstance:function(args) {
if(instance === undefined) {
instance =newSingleton(args);
}
returninstance;
}
};
return_static;
})();
varsingletonTest = SingletonTester.getInstance({ pointX: 5 });
console.log(singletonTest.pointX);// 輸出 5
其它實(shí)現(xiàn)方式
方法1:
functionUniverse() {
// 判斷是否存在實(shí)例if(typeofUniverse.instance === 'object') {
returnUniverse.instance;
}
// 其它內(nèi)容this.start_time = 0;
this.bang = "Big";
// 緩存Universe.instance =this;
// 隱式返回this}
// 測(cè)試varuni =newUniverse();
varuni2 =newUniverse();
console.log(uni === uni2);// true
方法2:
functionUniverse() {
// 緩存的實(shí)例varinstance =this;
// 其它內(nèi)容this.start_time = 0;
this.bang = "Big";
// 重寫構(gòu)造函數(shù)Universe =function() {
returninstance;
};
}
// 測(cè)試varuni =newUniverse();
varuni2 =newUniverse();
uni.bang = "123";
console.log(uni === uni2);// trueconsole.log(uni2.bang);// 123
方法3:
functionUniverse() {
// 緩存實(shí)例varinstance;
// 重新構(gòu)造函數(shù)Universe =functionUniverse() {
returninstance;
};
// 后期處理原型屬性Universe.prototype =this;
// 實(shí)例instance =newUniverse();
// 重設(shè)構(gòu)造函數(shù)指針instance.constructor = Universe;
// 其它功能instance.start_time = 0;
instance.bang = "Big";
returninstance;
}
// 測(cè)試varuni =newUniverse();
varuni2 =newUniverse();
console.log(uni === uni2);// true
// 添加原型屬性Universe.prototype.nothing =true;
varuni =newUniverse();
Universe.prototype.everything =true;
varuni2 =newUniverse();
console.log(uni.nothing);// trueconsole.log(uni2.nothing);// trueconsole.log(uni.everything);// trueconsole.log(uni2.everything);// trueconsole.log(uni.constructor === Universe);// true
方式4:
varUniverse;
(function() {
varinstance;
Universe =functionUniverse() {
if(instance) {
returninstance;
}
instance =this;
// 其它內(nèi)容this.start_time = 0;
this.bang = "Big";
};
} ());
//測(cè)試代碼vara =newUniverse();
varb =newUniverse();
alert(a === b);// truea.bang = "123";
alert(b.bang);// 123