← 中文资源

简体中文版本

私有构造函数实现单例

用 private 构造函数把 new 调用挡在类外,只保留一个静态工厂入口:两次获取返回同一实例,共享配置只初始化一次。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

true
[info] singleton configured once

实现说明

私有构造函数实现单例的核心是类 Logger。 顶层就这几处状态:first、second。

常见问题

运行时需要 npm、pip、cargo 之类帮忙吗?

不需要——包管理器在这里无事可做,没有任何声明。 状态都挂在模块顶层:first、second。

核心语句

first.write('info', 'singleton configured once');
Logger.instance = new Logger(['stdout']);
const second = Logger.get();

代码示例

type Level = 'debug' | 'info' | 'error';

class Logger {
  private static instance: Logger | undefined;
  private readonly sinks: string[];

  // The private constructor blocks external new Logger() calls, so
  // the static getter is the only way to obtain the shared instance
  private constructor(sinks: string[]) {
    this.sinks = sinks;
  }

  static get(): Logger {
    if (!Logger.instance) {
      Logger.instance = new Logger(['stdout']);
    }
    return Logger.instance;
  }

  write(level: Level, message: string): void {
    console.log(`[${level}] ${message}`);
  }
}

const first = Logger.get();
const second = Logger.get();
console.log(first === second);

first.write('info', 'singleton configured once');