TS 设计模式03 - 单例模式

时间:2022-07-22
本文章向大家介绍TS 设计模式03 - 单例模式,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1. 简介

单例模式的概念很简单,就是在整个程序中有且仅有一个实例。这种场景其实是很常见的,比如我们的程序中存放当前用户信息的类,就只有一个实例,这样从任何地方获取其中信息时,都是拿的同一个对象的信息,保证状态的一致性。

2. 饿汉式

在该类创建的时候就进行了实例化。

class Singleton {
    private name: string;
    private static instance: Singleton = new Singleton('singleton');
    private constructor(name: string) {
        this.name = name;
        // TODO 初始化逻辑
    }
    public static getInstance(): Singleton {
        return Singleton.instance;
    }

    show() {
        console.log(this.name);
    }
}

Singleton.getInstance().show();  // singleton

3. 懒汉式

在真正调用 getInstance 方法时,类才被真正实例化,更加节约空间。

class Singleton {
    constructor(name) {
        this.name = name;
        // TODO 初始化逻辑
    }
    static getInstance() {
        if (!Singleton.instance) {
            Singleton.instance = new Singleton('singleton');
        }
        return Singleton.instance;
    }
    show() {
        console.log(this.name);
    }
}
Singleton.getInstance().show(); // singleton

4. 模块化实现

其实真正在项目中使用时,因为我们都是用模块化编程,只需要模块抛出的是一个实例而不是类,那么一样能达到单例效果。单例是在模块被引入的时候进行实例化的,模块本身其实是可以直接导入或者使用懒加载的。

// export.ts
class Singleton {
    protected name: string;
    constructor(name) {
        this.name = name;
        // TODO 初始化逻辑
    }

    show() {
        console.log(this.name);
    }
}

export default new Singleton('singleton');
// import.ts
import singleton from './export';

singleton.show();

5.小结

其实单例的核心,就是全局共享一个实例。