

생성자 접근 차단: 생성자를 private으로 지정하여 외부에서 직접 객체를 생성하지 못하도록 막는다.
정적 인스턴스 보관: 클래스 내부에 static 필드로 인스턴스를 저장한다.
정적 메서드로 접근: getInstance() 같은 정적 메서드를 통해 인스턴스를 반환한다.
getInstance() 호출new로 생성class Singleton {
private static instance: Singleton;
private constructor() {
console.log("🟢 Singleton instance created");
}
static getInstance(): Singleton {
if (!this.instance) {
this.instance = new Singleton();
}
return this.instance;
}
public log(message: string) {
console.log(`📘 ${message}`);
}
}
const logger1 = Singleton.getInstance();
const logger2 = Singleton.getInstance();
console.log(logger1 === logger2); // true
class ModalController {
private static instance: ModalController;
private subscribers: ((visible: boolean) => void)[] = [];
private constructor() {}
static getInstance() {
if (!this.instance) this.instance = new ModalController();
return this.instance;
}
subscribe(fn: (visible: boolean) => void) {
this.subscribers.push(fn);
}
open() {
this.subscribers.forEach((fn) => fn(true));
}
close() {
this.subscribers.forEach((fn) => fn(false));
}
}
Object.freeze()Object.freeze() 메서드는 객체를 동결해 수정을 방지한다.const obj = {
prop: 42,
};
Object.freeze(obj);
obj.prop = 33;
// Throws an error in strict mode
console.log(obj.prop);
// Expected output: 42
Object.freeze()를 사용하면 해당 인스턴스를 불변 객체로 만들 수 있어, 외부에서 속성을 추가하거나 수정, 삭제하는 것을 방지할 수 있다.const instance = new Singleton();
Object.freeze(instance);
// a.mjs
console.log("module A loaded");
export const x = 1;
// b.mjs
import { x } from "./a.mjs";
import { x as x2 } from "./a.mjs"; // 다시 import
console.log(x === x2); // true
getInstance() 같은 정적 메서드를 통해 직접 인스턴스를 생성하고 참조한다.