Observer Pattern
- In Turkish
- Observer Deseni
In short
The observer pattern is a behavioral design pattern in which an object, the subject, automatically notifies a list of subscribers whenever its state changes.
What is the observer pattern?
The observer pattern defines a one-to-many relationship between objects. One object, the subject, keeps a list of interested objects, the observers, and calls each of them when something happens, such as its data changing. Observers can subscribe and unsubscribe at any time, and the subject doesn't need to know anything about them other than how to notify them.
In practice, the subject exposes methods like subscribe and unsubscribe and calls every registered callback in a notify step. Web developers use this pattern constantly: addEventListener in the DOM, event emitters in Node.js, and reactive state in UI frameworks all follow it. When a button is clicked or a stored value changes, every registered listener runs.
A newsletter is a good analogy: readers sign up, the publisher sends each new issue to everyone on the list, and readers can unsubscribe whenever they like. The publisher doesn't need to know who the readers are or what they do with the issue. This loose coupling lets you add new reactions to an event without changing the code that triggers it.
The observer pattern is often confused with publish-subscribe. In the observer pattern, observers register directly with the subject, and notification usually happens synchronously inside one program; in publish-subscribe, publishers and subscribers don't know about each other and communicate through a separate broker or message queue, often across services. A common pitfall is forgetting to unsubscribe, which keeps unused objects alive and causes memory leaks.
Key takeaways
- A subject notifies all its registered observers when its state changes.
- Observers can subscribe and unsubscribe at run time.
- It decouples the code that triggers an event from the code that reacts to it.
- DOM event listeners and Node.js event emitters are everyday examples.
- Unsubscribe observers that are no longer needed to avoid memory leaks.
Example
class Subject {
observers = [];
subscribe(observer) {
this.observers.push(observer);
return () => (this.observers = this.observers.filter((o) => o !== observer));
}
notify(value) {
this.observers.forEach((observer) => observer(value));
}
}
const price = new Subject();
const unsubscribe = price.subscribe((p) => console.log("New price:", p));
price.notify(42); // New price: 42
unsubscribe(); // stop listening when no longer neededReaders ask
What is the difference between the observer pattern and publish-subscribe?
In the observer pattern, observers subscribe directly to the subject that notifies them. In publish-subscribe, a broker or event channel sits in between, so publishers and subscribers never reference each other, which suits communication between separate services.
Where is the observer pattern used?
It is used in DOM event listeners, Node.js event emitters, reactive UI state management, spreadsheet cells that update when other cells change, and anywhere several parts of a program must react to the same event.
What are the downsides of the observer pattern?
Observers that are never unsubscribed can cause memory leaks, and long chains of notifications can make the flow of a program hard to follow and debug. The order in which observers run is also usually not guaranteed.
See also
- Design PatternSoftware Architecture, p. 13A design pattern is a proven, reusable solution to a common problem in software design, described as a general template rather than as finished code.
- Event-Driven ArchitectureSoftware Architecture, p. 18Event-driven architecture is a software design style in which services communicate by producing and reacting to events, such as an order being placed.
- CallbackProgramming Fundamentals, p. 7A callback is a function passed as an argument to another function, which then calls it later, for example when a task finishes or an event happens.
- DOMWeb Development, p. 13The DOM is the browser's in-memory tree of objects representing a web page, which JavaScript can read and change to update what the user sees.
- Message QueueBackend & APIs, p. 29A message queue is a component that stores messages from one service until another is ready to process them, so parts of a system can work asynchronously.
- MVCSoftware Architecture, p. 29MVC is an architectural pattern that splits an application into a Model for data and logic, a View for display, and a Controller that handles user input.
Spotted a mistake or something missing on this page?Suggest an edit