1. 什么是單例模式耀盗?
單例模式定義:一個(gè)類只能有一個(gè)實(shí)例锡溯,即使多次實(shí)例化該類汰翠,也只返回第一次實(shí)例化后的實(shí)例對(duì)象类少。單例模式能減少不必要的內(nèi)存開銷, 并且減少全局函數(shù)和變量沖突。
2. 代碼實(shí)現(xiàn)
以下實(shí)現(xiàn)的單例模式均為“惰性單例”:惰性單例指的是在需要的時(shí)候才創(chuàng)建對(duì)象實(shí)例碗誉。惰性單例在實(shí)際開發(fā)中非常有用召嘶,是單例模式的重點(diǎn)。instance實(shí)例對(duì)象總是在我們調(diào)用Singleton.getInstance的時(shí)候才被創(chuàng)建哮缺,而不是在頁面加載好的時(shí)候就創(chuàng)建弄跌。
javascript 實(shí)現(xiàn)
function Singleton(name){
this.name = name;
this.instance = null;
}
Singleton.prototype.getName = function(){
console.log(this.name);
};
Singleton.getInstance = function(name){
if(! this.instance){
this.instance = new Singleton(name);
}
return this.instance;
};
var a = Singleton.getInstance('a');
var b = Singleton.getInstance('b');
console.log(a === b);//true
console.log(a.getName(), b.getName());//a a
ES6 實(shí)現(xiàn)
class Singleton {
constructor(name) {
this.name = name;
}
static getInstance(name) {
// ES6中可以使用static方法代替閉包存儲(chǔ)單例
if(!Singleton.instance) {
Singleton.instance = new Singleton(name)
}
return Singleton.instance;
}
getName() {
return this.name;
}
}
const a = Singleton.getInstance('a');
const b = Singleton.getInstance('b');
console.log(a === b);//true
console.log(a.getName() === b.getName());//true
console.log(a.getName(), b.getName());//a a