Part 5 of 6 · 2 min read
In practice
Events, buses and Java's tools.
Observer in practice
The pattern appears in many forms. User interface toolkits use listeners for clicks. Message systems use publish and subscribe, which adds a middle service between subject and observers so that they do not know each other at all (a case study in Level 7). Event buses in applications route typed events to handlers. In each, the core is the same: a list of interested parties and a notify loop.
Design choices to state in an interview:
- Who triggers the notification? The subject should do it itself after a change, so a client cannot forget. GoF lists this choice and its trade-off, since a client that triggers it risks missing a call.
- Push or pull? Say which and why.
- Order and failure. Observers should not depend on the order in which they are called. If one throws, decide whether the rest still run. A safe loop catches exceptions per observer and logs them.
- Threads. State whether observers run on the caller's thread or on a separate one. Calling on the caller's thread is simple but can slow the subject. A thread pool keeps the subject fast but makes ordering weaker.
Java's older built-in Observable class and Observer interface are deprecated, so write your own small interface, as here.
Interview angle
Answer in your head first, then open it.
What is the Observer pattern?
A subject keeps a list of observers and notifies them when its state changes, so it does not depend on their concrete classes.
Push or pull?
Push sends the data with the notification. Pull sends only a signal and observers ask for details.
What can go wrong?
Changing the list while notifying, calling observers under a lock, forgotten unsubscribes, and cascades of updates.
Check yourself: 1. Who should trigger the notification, and why? 2. What should a safe notify loop do if one observer throws?
Words you will meet
| Word | Meaning |
|---|---|
| Subject | The object that changes and notifies |
| Observer | An object that is told about changes |
| Subscribe | Add an observer to the subject's list |
| Push and pull | Sending the data, or only a signal |
| Alien method | A method the caller cannot know the behaviour of |