A software design pattern where an object (subject) maintains a list of its dependents (observers) and notifies them of state changes.
class Subject {
constructor() {
this.observers = [];
}
// Register observer
subscribe(observer) {
this.observers = [...this.observers, observer];
}
// Unsubscribe observer
unsubscribe(observer) {
this.observers = this.observers.filter(obs => obs !== observer);
}
// Notify all observers
notify(data) {
this.observers.forEach(observer => observer.update(data));
}
}
class Observer {
constructor(id) {
this.id = id;
}
// Handle update
update(data) {
console.log(`Observer ${this.id} received:`, data);
}
}
Common use cases include event systems, model-view-controller (MVC) frameworks, and reactive programming. It's also used in JavaScript frameworks like Vue.js and Knockout.js for data binding.
While conceptually similar, in Publish/Subscribe patterns messages are often addressed to a topic, whereas in Observer pattern observers are coupled to specific subjects. The pub/sub pattern typically has looser coupling between publishers and subscribers.
Yes, the observer pattern is used in React's context API and in state management libraries like MobX. It helps components react to changes in state by observing updates and re-rendering when needed.