/** * 饿汉模式 * 特点:类加载时就初始化。 */ class SingletonMode1 { private static instance = new SingletonMode1() // 将 constructor 设为私有属性,防止 new 调用 private constructor() { } static getInstance(): SingletonMode1 { return this.instance } } /** * 懒汉模式 * 特点:需要时才创建对象实例。 */ class SingletonMode2 { private static instance: SingletonMode2 private constructor() { } static getInstance(): SingletonMode2 { if (!this.instance) { this.instance = new SingletonMode2() } return this.instance } }