Understanding the Observer Pattern through a Talk‑Show Analogy and Java Implementation
This article explains the Observer design pattern by comparing it to a talk‑show scenario, then details its Java implementation—including Observable and Observer classes, notification mechanisms, code examples, common pitfalls, asynchronous extensions, and practical e‑commerce applications—in a clear, step‑by‑step manner.
1. Talk‑Show Analogy
The article starts with a humorous analogy: a talk‑show actor is the Observable (the subject), while the "lead laughers" and the audience act as Observers . When the actor performs well, the lead laughers "flash the light" and the audience press a remote button, illustrating how multiple observers react to a single subject.
2. Observer Pattern Definition
According to the GoF book, the Observer pattern defines a one‑to‑many dependency so that when one object changes state, all its dependents are automatically notified. It is also known as publish‑subscribe or listener callbacks.
Java provides built‑in support via the java.util.Observable class and the java.util.Observer interface, which can use push or pull data transfer.
3. How Observable Works
To become observable, a class simply extends Observable . The class gains methods to add, store, and remove observers, and to notify them.
Add Observer
The method addObserver registers an observer.
Store Observers
Observers are kept in a Vector collection inside Observable .
Remove Observer
The method deleteObserver deregisters an observer.
Notify Observers
Two methods are provided: notifyObservers() (no argument) and notifyObservers(Object arg) (pushes data). The notification process consists of three steps:
Check whether the observable’s state has changed.
Retrieve all registered observers from the vector.
Iterate over them and call each observer’s update method.
Code example (kept intact):
public void notifyObservers(Object var1) {
Object[] var2;
synchronized(this) {
// when setChange() is called, this.changed = true
if (!this.changed) {
return;
}
// get all observers
var2 = this.obs.toArray();
// reset change flag
this.clearChanged();
}
// notify each observer
for (int var3 = var2.length - 1; var3 >= 0; --var3) {
((Observer)var2[var3]).update(this, var1);
}
}setChanged and clearChanged
Before notifying, the observable must call setChanged() to mark that its state has changed; otherwise, notifyObservers does nothing. The method clearChanged() resets the flag.
protected synchronized void clearChanged() {
this.changed = false;
}4. Observer Implementation
An observer implements the Observer interface:
public interface Observer {
void update(Observable var1, Object var2);
}The update method contains the reaction logic (e.g., flashing a light).
5. Push vs. Pull
Using the argument version of notifyObservers implements a push model; using the no‑argument version implements a pull model where observers query the observable for data.
6. Full Code Example
The article defines three concrete classes: Leader (lead laughers), Viewer (audience), and Actor (the observable). The actor adds leaders and viewers as observers, calls setChanged() and notifyObservers(arg) after each joke, causing all observers to react.
7. Design‑Pattern Critiques
Observers must be explicitly registered, exposing implementation details.
Observable is a concrete class, not an interface, violating the “program to an interface” principle.
Java’s single inheritance limits reuse when a class needs both observable and other behaviours.
setChanged() is protected, forcing inheritance rather than composition.
8. Architectural Concerns
Problems discussed include synchronous blocking notifications, cross‑process communication, and cross‑machine communication. Suggested solutions are:
Run notifyObservers in a separate thread for async delivery.
Use Google Guava EventBus or a message‑queue for decoupled, distributed notification.
9. E‑Commerce Application
Inventory can be an observable; stock‑in documents act as observers. When inventory changes, observers generate stock‑in records or send alerts, demonstrating a practical use case.
10. Conclusion
The article wraps up by summarizing the talk‑show analogy, the mechanics of Observable and Observer, the identified design issues, and the potential extensions for asynchronous, cross‑process, and cross‑machine scenarios, ending with a call for discussion and a link to download the source code.
Wukong Talks Architecture
Explaining distributed systems and architecture through stories. Author of the "JVM Performance Tuning in Practice" column, open-source author of "Spring Cloud in Practice PassJava", and independently developed a PMP practice quiz mini-program.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.