Private Constructors Enforce A Singleton
Force one shared instance with a private constructor and a static getter, so new Logger() cannot compile outside the class.
Code
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');Output
Captured from a sandboxed run of this snippet in the build pipeline.
true
[info] singleton configured onceThe private constructor’s one door
Logger’s constructor is marked private, so new Logger(...) cannot compile outside the class body — the static getter Logger.get() is the only entry point. Inside get(), the guard if (!Logger.instance) { Logger.instance = new Logger(['stdout']); } builds the shared instance exactly once, with its sinks array fixed to ['stdout'].
What the run shows
true
[info] singleton configured once
first === second prints true because both constants were handed the same cached Logger.instance. The second line is first.write('info', 'singleton configured once'), whose write method logs `[${level}] ${message}` — the [info] prefix comes from that template, not from any list of blocks. Sharing one instance is what lets sink configuration stay single-shot: the constructor ran one time, however many call sites ask for the logger.
The lines that pin the identity
static get(): Logger {
if (!Logger.instance) {
Logger.instance = new Logger(['stdout']);
}
return Logger.instance;
}
Because the field is private static instance: Logger | undefined, no outside code can reset or pre-seed it — the class fully owns its singleton lifecycle.
Interactive Tools for This Topic
FAQ
- Does the runtime need any help from npm, pip, cargo, or the like?
- No — the package manager has nothing to do here; nothing is declared. Its state lives in module-level bindings: `first`, `second`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.