Observer & Singleton Patterns
How should you implement an Observer Pattern for handling asynchronous events?
class AsyncSubject {
constructor() {
this.observers = new Set();
}
subscribe(observer) {
this.observers.add(observer);
return () => this.observers.delete(observer);
}
async notify(data) {
const notifications = Array.from(this.observers)
.map(observer => observer.update(data));
await Promise.all(notifications);
}
}
class AsyncObserver {
async update(data) {
// Handle async update
await processData(data);
}
}