One-to-Many Relationships
You'll learn how a single subject can notify multiple independent observers simultaneously, forming the foundation of reactive programming patterns.
The Core Concept
In the Observer pattern, "one-to-many" describes the relationship between one subject (the observable) and many observers (the subscribers). When the subject's state changes, it automatically notifies all registered observers, and each observer reacts independently according to its own logic.
Think of it like a newsletter: one publisher (subject) sends updates to many subscribers (observers). Each subscriber receives the same notification but might respond differently—one might archive it, another might share it, and another might delete it. The publisher doesn't know or care what each subscriber does; it just sends the update to everyone on the list.
How It Works
class NewsSubject {
constructor() {
this.observers = [];
}
subscribe(observer) {
this.observers.push(observer);
}
notify(news) {
// One notification → many observers
this.observers.forEach(observer => observer.update(news));
}
}
const subject = new NewsSubject();
// Multiple independent observers
subject.subscribe({ update: (news) => console.log(`Logger: ${news}`) });
subject.subscribe({ update: (news) => console.log(`Alert: ${news}`) });
subject.subscribe({ update: (news) => console.log(`Archive: ${news}`) });
// One call, three reactions
subject.notify("Breaking news!");
// Logger: Breaking news!
// Alert: Breaking news!
// Archive: Breaking news!
Each observer maintains its own state and behavior. The subject simply maintains a list and broadcasts to all. This decoupling is powerful: you can add or remove observers without changing the subject.
Key Takeaway: One-to-many relationships let a single subject broadcast state changes to multiple independent observers, enabling loosely coupled, reactive systems where components respond to changes without tight dependencies.