Observer Pattern
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified automatically.
Intent & Objective
Establish a subscription mechanism to notify multiple observer objects about any events that happen to the subject object they are listening to.
"When an author posts a new video or update, all subscribed followers receive instant automated notifications."
"A single smoke detector trigger broadcasts an alert that immediately activates every alarm horn and sprinkler across the entire facility."
"When stock prices change, thousands of algorithmic traders and mobile apps are notified simultaneously."
"New git commits or urgent bug tickets automatically trigger notifications to all subscribed developers in the team channel."
The Problem
Polling: clients repeatedly query an object in tight loops checking if its state changed, burning CPU and network cycles.
The Solution
The Subject stores a list of subscriber interfaces. Whenever an interesting event occurs, the subject loops through the list and calls `update()` on each observer.
Key Participants & Architectural Roles
Code Samples (Traditional OOP vs Functional Programming)
Available in C++, Python, and JavaParadigm Contrast: Traditional OOP vs Functional / Data-Oriented
In OOP, Observer relies on interfaces and event listener lists. In Functional Programming, Observer is expressed as Functional Reactive Programming (FRP), Streams (like Rx / Project Reactor), Signals, or event-emitter callback lists.
Advantages
- ✓ Open/Closed Principle: you can introduce new subscribers without changing the publisher code
- ✓ Establishes dynamic runtime relationships between objects
Trade-offs
- ✗ Subscribers are notified in random order
- ✗ Can lead to memory leaks if observers are not unsubscribed (Lapsed Listener Problem)
When to Apply
- → When changes to the state of one object may require changing other objects, and the actual set of objects is unknown beforehand or changes dynamically
- → In UI event systems (button clicks, keyboard events) and reactive architectures
When to Avoid
- ! When state changes are strictly point-to-point and deterministic