Behavioral Patterns • Observer PatternEasy⏱️ ~2 min
Observer Pattern: Definition and Problem
Definition
Observer Pattern defines a one-to-many dependency between objects so that when one object (the subject) changes state, all its dependents (observers) are notified and updated automatically.
Problem It Solves:
When one object needs to notify multiple other objects about state changes without creating tight coupling between them. Without this pattern, the subject would need direct references to all dependent objects and know their concrete types, violating the Open/Closed Principle.
Real-World Analogy: A newspaper publisher (subject) maintains a list of subscribers (observers). When a new edition is published, all subscribers automatically receive it without the publisher needing to know what each subscriber does with the newspaper.
Key Characteristics:First, the subject maintains a list of observers and provides methods to attach/detach them.
Second, observers implement a common interface with an update method.
Third, the subject notifies all registered observers when its state changes.
Fourth, observers can pull additional data from the subject if needed (pull model) or receive it in the notification (push model).
Interview Tip: Always clarify whether to use push (subject sends data) or pull (observers query subject) model. Push is simpler but less flexible, while pull gives observers more control but requires subject reference.
💡 Key Takeaways
✓Defines one-to-many dependency between subject and observers
✓Subject notifies observers automatically on state changes
✓Observers implement common interface for updates
✓Decouples subject from concrete observer classes
📌 Examples
1Social media notifications when someone posts
2Stock price updates to multiple display widgets
3Event listeners in UI frameworks