class Subject {
constructor() {
this.items = [];
}
registerObserver(observer) {
this.items.push(observer);
}
notifyObservers() {
for (let i = 0; i < this.items.length; i++) {
this.items[i].update(i);
}
}
}
class Observer {
constructor(subject) {
subject.registerObserver(this);
}
update(index) {
console.log(`receive${index}`);
}
}
const s = new Subject();
new Observer(s);
new Observer(s);
s.notifyObservers();
网友评论