Observer Pattern
- •
What it is
- •
a behavioral pattern establishing a one-to-many relationship: when one object (the Subject) changes state, all objects observing it (the Observers) are automatically notified and updated
- •
- •
Analogy
- •
a news subscription — when new news is published, every subscriber is notified
- •
- •
How it works
- •
an Observer registers with a Subject (
registerObserver()); when the Subject's state changes, it callsupdate()on every registered Observer; the Observer can then pull data from the Subject, or receive it pushed directly
- •
- •
Benefits
- •
automatic notification (no manual updates needed per object), flexible (observers can be added/removed without changing the subject), subject and observers are independently testable, widely used in real frameworks (Swing, JavaBeans, RxJS, Node's EventEmitter)
- •
- •