구성 요소
observers
: 알림을 받을 Subscriber 목록subscribe(fn)
: 옵저버 등록unsubscribe(fn)
: 옵저버 제거notify(data)
: 등록된 옵저버 모두에게 이벤트 전파notify()
호출 시 자동으로 실행된다.동작 방식
subscribe()
를 호출해 옵저버를 등록할 수 있다.notify()
를 호출해 모든 등록된 옵저버에게 알림을 보낸다.unsubscribe()
로 제거한다.type Observer = (data: any) => void;
class Publisher {
private observers: Observer[] = [];
// 옵저버 등록
subscribe(observer: Observer) {
this.observers.push(observer);
}
// 옵저버 제거
unsubscribe(observer: Observer) {
this.observers = this.observers.filter((fn) => fn !== observer);
}
// 모든 옵저버에게 이벤트 전파
notify(data: any) {
this.observers.forEach((observer) => observer(data));
}
}
const newsPublisher = new Publisher();
const subscriberA = (data: any) => console.log("📰 A received:", data);
const subscriberB = (data: any) => console.log("📰 B received:", data);
newsPublisher.subscribe(subscriberA);
newsPublisher.subscribe(subscriberB);
newsPublisher.notify("🚨 Breaking News!");
// 출력:
// 📰 A received: 🚨 Breaking News!
// 📰 B received: 🚨 Breaking News!
newsPublisher.unsubscribe(subscriberA);
newsPublisher.notify("🗞 Daily Update");
// 출력:
// 📰 B received: 🗞 Daily Update
Redux의 store.subscribe()
const unsubscribe = store.subscribe(() => {
console.log(store.getState());
});
// 구독을 해제할 때
unsubscribe();
store.subscribe()
는 구독자 등록notify()
와 유사한 방식으로 모든 리스너에게 알림 전파React Router v5의 history.listen()
import { createBrowserHistory } from "history";
const history = createBrowserHistory();
history.listen((location, action) => {
console.log("📍 라우트 변경 감지:", location.pathname);
});
listen()
메서드는 옵저버를 등록하는 subscribe()
역할subscribe()
, unsubscribe()
, notify()
메서드를 통해 주체(Publisher)가 구체적인 구독자(Observer)에 대해 알 필요 없이 변화만 전파한다.