옵저버 패턴(Observer Pattern)은 한 객체(Subject)의 상태가 변하면 그 객체에 의존하는 모든 객체(Observer)들에게 자동으로 알림이 가고 상태가 갱신되는 1:N(일대다) 의존성을 정의하는 패턴입니다. 유튜버가 새 영상을 올릴 때마다 구독자(Observer)들의 스마트폰으로 알림이 오는 '발행-구독(Pub/Sub)' 메커니즘이 바로 이 패턴의 대표적인 예입니다.
1. 옵저버 패턴 구조 (Observer UML)
Subject는 어떤 Observer가 자신을 구독하고 있는지 구체적인 타입을 알 필요 없이, 공통된 update() 인터페이스만 호출하면 됩니다. 이를 통해 두 객체는 느슨한 결합(Loose Coupling)을 유지합니다.
2. 옵저버 패턴의 핵심 포인트
💡 유연한 결합도
새로운 종류의 알림 수신기(이메일, 슬랙, 카카오톡 등)를 추가하더라도 Subject 쪽 코드는 전혀 수정할 필요가 없습니다. 새 수신기가 Observer 인터페이스만 구현하고 attach()를 통해 등록하기만 하면 됩니다. (개방-폐쇄 원칙, OCP 준수)
// 📂 Subject.js (JavaScript)
// 자바스크립트에서는 인터페이스가 없으므로 클래스로 흉내를 냅니다.
class Youtuber {
constructor(name) {
this.name = name;
this.subscribers = []; // Observer들을 담을 배열
this.latestVideo = "";
}
// 구독 (attach)
subscribe(subscriber) {
this.subscribers.push(subscriber);
console.log(`[시스템] ${subscriber.name}님이 ${this.name} 채널을 구독했습니다.`);
}
// 구독 취소 (detach)
unsubscribe(subscriber) {
this.subscribers = this.subscribers.filter(sub => sub !== subscriber);
console.log(`[시스템] ${subscriber.name}님이 구독을 취소했습니다.`);
}
// 새 영상 업로드 시 알림 (notify)
uploadVideo(title) {
this.latestVideo = title;
console.log(`\n▶️ [${this.name}] 새 영상 업로드: "${title}"`);
this.notifyAll();
}
// 모든 구독자에게 상태 업데이트를 전파
notifyAll() {
this.subscribers.forEach(sub => {
sub.update(this.name, this.latestVideo);
});
}
}
// 📂 Observer.js
class Subscriber {
constructor(name) {
this.name = name;
}
// Subject로부터 호출받을 update 메서드
update(youtuberName, videoTitle) {
console.log(`🔔 [${this.name}의 스마트폰] 알림: ${youtuberName}님의 새 영상 "${videoTitle}"이(가) 올라왔습니다!`);
}
}
// 📂 main.js
const techChannel = new Youtuber("IT 꿀팁");
const user1 = new Subscriber("민수");
const user2 = new Subscriber("지영");
const user3 = new Subscriber("철수");
techChannel.subscribe(user1);
techChannel.subscribe(user2);
techChannel.subscribe(user3);
// 영상을 업로드하면 모든 구독자에게 자동으로 알림이 갑니다!
techChannel.uploadVideo("2026년 최신 웹 프레임워크 비교");
techChannel.unsubscribe(user2);
// 구독 취소한 지영이에게는 알림이 가지 않습니다.
techChannel.uploadVideo("개발자가 꼭 알아야 할 디자인 패턴");