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. 业务方法...
}

 

posted @ 2025-12-29 14:06  howhy  阅读(39)  评论(0)    收藏  举报