單例模式確保類全域僅有一實例,並提供全域存取點。本文展示從經典閉包寫法到現代 ES6 模組單例、懶載入、可測試設計的演進,並討論單例濫用的反模式風險。
var SingletonTester = (function() {
// 私有建構函數
function Singleton(options) {
options = options || {};
this.name = 'SingletonTester';
this.pointX = options.pointX || 6;
this.pointY = options.pointY || 10;
}
// 單例實例緩存
let instance;
// 公開靜態介面
return {
name: 'SingletonTester',
getInstance: function(options) {
if (!instance) {
instance = new Singleton(options);
}
return instance;
},
// 測試用:重置單例 (僅開發/測試環境暴露)
_reset: function() { instance = null; }
};
})();
// 使用
const s1 = SingletonTester.getInstance({ pointX: 5 });
const s2 = SingletonTester.getInstance({ pointY: 20 }); // 忽略參數,返回同一實例
console.log(s1 === s2); // true
console.log(s1.pointX); // 5 (首次參數生效)
// singleton.js
class ConfigManager {
constructor() {
if (ConfigManager._instance) {
return ConfigManager._instance;
}
this.settings = new Map();
this.loadDefaults();
ConfigManager._instance = this;
}
loadDefaults() {
this.set('apiBase', '/api/v1');
this.set('timeout', 5000);
}
set(key, value) { this.settings.set(key, value); }
get(key) { return this.settings.get(key); }
has(key) { return this.settings.has(key); }
// 靜態工廠方法 (可選,直觀語意)
static getInstance() {
return new ConfigManager();
}
}
// 凍結防止意外修改原型
Object.freeze(ConfigManager.prototype);
module.exports = ConfigManager;
// 使用
const ConfigManager = require('./singleton');
const config = ConfigManager.getInstance();
config.set('debug', true);
// 其它模組 require 同一文件,獲取同一實例
優勢:ES6 模組天然單例 (模組緩存)、語法清晰、支援 Tree Shaking、TypeScript 友善。
class HeavyService {
constructor() {
this.expensiveResource = this.initExpensiveResource(); // 延遲到首次實例化
}
initExpensiveResource() { /* 大量計算、建立連線池、載入模型 */ }
doWork() { /* ... */ }
}
// 代理模式包裝懶載入
const HeavyServiceProxy = (function() {
let instance;
return {
getInstance() {
if (!instance) instance = new HeavyService();
return instance;
},
// 允許注入 Mock (測試關鍵)
_setInstanceForTest(mock) { instance = mock; }
};
})();
單例全域狀態導致測試相互干擾。解決方案:
Singleton.getInstance(),而是由外部傳入實例。_reset() 或 _setInstance(),beforeEach 呼叫。jest.mock('./singleton') 自動 Mock 全模組。Math、DateUtils 等直接用靜態方法或純函數模組。class Logger {
private static _instance: Logger;
private logs: string[] = [];
private constructor() {}
static getInstance(): Logger {
if (!Logger._instance) Logger._instance = new Logger();
return Logger._instance;
}
log(msg: string) { this.logs.push(`[${new Date().toISOString()}] ${msg}`); }
getLogs(): ReadonlyArray { return this.logs; }
}
// 使用
Logger.getInstance().log('App started');
單例模式威力強大,但「全域唯一」也是雙面刃。善用模組系統天然單例、依賴注入、測試重置機制,讓單例成為架構基石而非技術債。