Observer and Pub/Sub Workshop
Retrieval Prompts
- State the three required capabilities of a subject (publisher).
- State the minimum interface a classical observer must satisfy.
- Name two memory-management hazards of naive Observer and a mitigation for each.
- Explain push versus pull notification in one sentence each.
- State the line at which Observer becomes Pub/Sub in your mind.
Compare and Distinguish
- Observer versus direct method call
- Observer versus Pub/Sub bus with topics
- push versus pull notification
- synchronous versus asynchronous notification
- strong reference versus weak reference to observers
Common Mistake Check
For each snippet, find the bug:
- A subject iterates
this.listenersdirectly while calling eachupdate, and a listener callsunsubscribe(self)insideupdate. - A GUI widget registers itself with a model in its constructor and never unsubscribes.
- An
updatemethod calls the subject's setter, which re-entersnotify. - "Two observers must fire in this order; it works now because I added B after A."
- Observer exception bubbles up, subject never notifies the remaining listeners.
Mini Application
Implement these three deliberately, in order:
- Classical Observer: a
TempSensorwithsubscribe,unsubscribe, andpublish. One observer formats to Celsius, another logs anomalies, a third increments a metric counter. - Defensive Observer: extend the above to snapshot listeners, isolate observer exceptions, and return an unsubscribe token from
subscribe. - Topic-based bus: replace the sensor's direct Observer with a small
EventBuskeyed by topic (temp.updated,temp.anomaly). Show that the sensor no longer knows any subscriber classes.
Contract Drill
For your pub/sub bus:
- Define a schema for one event (e.g.,
OrderPlaced { id, customerId, total, placedAt }). - Write three consumers that rely on it.
- Evolve the event (add a field). Which consumers still work? Which need changes?
- Write a one-paragraph policy for schema evolution in your bus.
Pitfall Drill
Deliberately cause each failure mode in a controlled test, then fix:
- Re-entrant notification that blows the stack.
- Subscriber-list mutation during iteration.
- Observer leak: subject keeps a dead consumer alive, confirmed by a weak-reference probe.
- Silent observer failure: one throws, the rest stop getting notified.
Evidence Check
This page is complete only if you can demonstrate each fix with a test, not by argument.