Skip to content

单例模式

单例模式是一种创建型设计模式。让你能保证一个类只有一个实例,并提供访问该实例的全局节点。

特点

  1. 唯一实例:确保一个类只有一个实例。
  2. 全局访问点:提供一个全局访问点来获取该实例。
  3. 线程安全:在多线程环境下,确保实例的唯一性。

单例模式解决了两个问题,所以违反了单一职责原则

  • 保证一个类只有一个实例
  • 为该实例提供一个全局访问节点

实现方式

单例模式的实现都是基于以下相同的两个步骤:

  1. 将默认构造函数设置为私有,防止其他对象使用单例的new运算符。
  2. 新建一个静态方法作为构造函数,在访问该单例实例时,如果没有创建单例,创建单例并且返回实例对象。如果已有实例对象,则直接返回实例对象

类单例的创建又分为懒汉模式饿汉模式

饿汉模式代码实现:

typescript
class SingletonEager {
    // 在类加载时立即创建实例(静态属性)
    private static instance: SingletonEager = new SingletonEager();

    // 私有构造函数,防止外部实例化
    private constructor(public name: string = "Eager Instance") {}

    // 提供全局访问点
    public static getInstance(): SingletonEager {
        return SingletonEager.instance;
    }
}

懒汉模式代码实现:

typescript
class SingletonLazy {
    // 延迟初始化:初始为 null
    private static instance: SingletonLazy | null = null;

    // 私有构造函数
    private constructor(public name: string = "Lazy Instance") {}

    // 第一次调用时才创建实例
    public static getInstance(): SingletonLazy {
        if (!SingletonLazy.instance) {
            SingletonLazy.instance = new SingletonLazy();
        }
        return SingletonLazy.instance;
    }
}