單例模式之所以這麼叫,是因爲它限制一個類只能有一個實例化對象。經典的實現方式是,創建一個類,這個類包含一個方法,該方法在沒有對象存在時,將會創建一個新的實例對象。如果對象存在,這個方法只是返回這個對象的引用。
let singleton = (() => {
let instance;
function init() {
// 私有變量和方法
let privateString = 'I am private';
function privateMethod() {
console.log('I am a private method');
}
// 公有變量和方法
return {
publicString: 'I am public',
publicMethod: () => {
console.log('I am a public method');
}
};
}
let _value = {
// 如果存在獲取此單例實例,如果不存在創建一個單例實例
getInstance: () => {
if (!instance) {
instance = init();
}
return instance;
}
};
return _value;
})();
let myInstance = singleton.getInstance();
console.log(myInstance.publicString);
myInstance.publicMethod();
如果需要擴展這個唯一的實例,可以重新定義獲取實例的方法
singleton.getInstance = () => {
if (!this._instance) {
if (isFoo) {
this._instance = new FooSingleton();
} else {
this._instance = new BasicSingleton()
}
}
}
爲什麼需要單例模式,而不是直接定義一個靜態對象
const object = {
publicString: 'I am public',
publicMethod: () => {
console.log('I am a public method');
}
}
因爲單例可以懶構造,在真正用到之前(調用getInstance()之前),單例模式不需要分配資源或者內存。