让前端飞TypeScript 极简教程

实现一个ts单例模式基类(支持代码提示、禁止二次实例化)

2023-10-15  本文已影响0人  来一斤BUG

先贴出我的代码,后面再讲讲为什么要这么做:

class Singleton {
    // 实例
    private static _instance: Singleton;
    // 是否是通过getInstance实例化
    private static _instantiateByGetInstance: boolean = false;
    
    /**
     * 获取实例
     */
    public static getInstance<T extends Singleton>(this: (new () => T) | typeof Singleton): T {
        const _class = this as typeof Singleton;
        if (!_class._instance) {
            _class._instantiateByGetInstance = true;
            _class._instance = new _class();
            _class._instantiateByGetInstance = false;
        }
        return _class._instance as T;
    }
    
    /**
     * 构造函数
     * @protected
     */
    protected constructor() {
        if (!(this.constructor as typeof Singleton)._instantiateByGetInstance) {
            throw new Error("Singleton class can't be instantiated more than once.");
        }
    }
}

我在网上搜索了一遍,大多数文章里的ts单例模式或多或少是不够完美的,我的单例模式有以下几个优点:

  1. 子类可以直接继承此Singleton类,无需其他多余代码,比如
class TestClass extends Singleton {
    
}
  1. 支持IDE代码提示
class TestClass extends Singleton {
    testFunc() {
        
    }
}
代码提示
  1. 禁止使用new关键字实例化


    禁止实例化

接下来讲讲为什么要这么写

class TestClass extends Singleton {
    testFunc() {
        new TestClass();
    }
}
抛出错误
上一篇 下一篇

猜你喜欢

热点阅读