Define a one-to-many dependency so that when one object changes state, all dependents are notified. You need event-driven updates. Multiple
Observer
Overview
Define a one-to-many dependency so that when one object changes state, all dependents are notified.
When to use
- You need event-driven updates.
- Multiple components react to the same change.
Java example
TypeScript example
Pros and cons
Pros:
- Loose coupling between subject and observers.
- Easy to add new listeners.
Cons:
- Hard to debug update order.
- Potential memory leaks from subscriptions.
Common pitfalls
- Forgetting to unsubscribe.
- Triggering cascading updates unintentionally.
Related patterns
title: Observer sidebar_position: 7 tags: [design-patterns, behavioral]
Observer
Overview
Define a one-to-many dependency so that when one object changes state, all dependents are notified.
When to use
- You need event-driven updates.
- Multiple components react to the same change.
Java example
TypeScript example
Pros and cons
Pros:
- Loose coupling between subject and observers.
- Easy to add new listeners.
Cons:
- Hard to debug update order.
- Potential memory leaks from subscriptions.
Common pitfalls
- Forgetting to unsubscribe.
- Triggering cascading updates unintentionally.