实现说明
私有构造函数实现单例的核心是类 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');