주체가 어떤 객체(subject)의 상태 변화를 관찰하다가
상태변화가 있을 때마다 메서드 등을 통해 옵저버 목록에 있는 옵저버들에게 변화를 알려주는 디자인 패턴이다.

관찰을 하는 구독 객체
관찰 대상의 주제 객체 가 있다
입주 희망자(주제 객체)는 방이 있는지 공인중개사(구독 객체)에 일일히 물어봐야 하는 번거로움이 있다

주제 객체가 방이 생기면 주제 객체 = subscriber에게 방이 나왔다고 공지notifyAll() 하게 된다.
더 이상 공지notifyAll() 받지 않고 싶을때, subscriber는 unsubscribe() 하게 된다
class Subject{
constructor(){
this.oberservers=[];
}
getObserverList(){
return this.observers;
}
subscribe(observer){ // 옵저버 리스트에 옵저버를 푸쉬하는 역할
this.observers.push(observer)
}
unsubscribe(observer){ // 옵저버 제외
this.observers = this.observers.filter((obs) => obs !== observer)
}
notifyAll(){ // 옵저버 리스트 (= 부동산 소개를받는)에 알림을 주는
this.observers.forEach((subscriber) =>{
try{
subscriber.update(this.constructor.name);
}catch (err){
console.error("error",err);
}
});
}
}
class Observer{
constructor(name){
this.name = name;
}
update(subj){ // 업데이트, 주제 객체 함수 등록
console.log(`${this.name} : notified from ${subj} class!`);
}
}
const subj = new Subject()
const a = new Observer("A");
const b = new Observer("B");
const c = new Observer("C");
subj.subscribe(a);
subj.subscribe(b);
subj.subscribe(c);
subj.notifyAll();
subj.unsubscribe(c);
subj.notifyAll();
https://github.com/wnghdcjfe/csnote
https://victorydntmd.tistory.com/292
https://www.youtube.com/watch?v=boXNtyeOzuc
https://www.youtube.com/watch?v=1UxRkggQwbs