js 单例模式
class Singleton { // 1. 使用私有静态属性 static #instance = null; // 2. 防止直接 new constructor() { if (Singleton.#instance) { throw new Error('Use getInstance() instead of new'); } Singleton.#instance = this; // 初始化逻辑 this.initialized = false; } // 3. 获取单例实例 static getInstance() { if (!Singleton.#instance) { Singleton.#instance = new Singleton(); } return Singleton.#instance; } // 4. 添加实际的方法 initialize(config) { if (!this.initialized) { this.config = config; this.initialized = true; } } // 5. 业务方法... }

浙公网安备 33010602011771号