What is the Observer pattern? Explain with a cricket score example.
A subject keeps a list of observers and tells all of them when its state changes. Observers subscribe and unsubscribe at runtime, and the subject does not need to know what they do with the news.
Explain it simply
A live cricket score. The scoreboard is the subject. The mobile app, the TV graphic and the radio commentator all subscribe. When a wicket falls, the scoreboard announces it once and everybody who subscribed gets the update. The scoreboard does not know or care how each one uses it.
Example
interface ScoreListener { void onScore(int runs, int wickets); }
class Match {
private final List<ScoreListener> listeners = new ArrayList<>();
private int runs, wickets;
void subscribe(ScoreListener l) { listeners.add(l); }
void unsubscribe(ScoreListener l) { listeners.remove(l); }
void wicket(int runsOnBall) {
runs += runsOnBall;
wickets++;
for (ScoreListener l : listeners) l.onScore(runs, wickets);
}
}
Match m = new Match();
m.subscribe((r, w) -> System.out.println("App: " + r + "/" + w));
m.subscribe((r, w) -> System.out.println("TV: " + r + "/" + w));
m.wicket(0);
// App: 0/1
// TV: 0/1The Match class depends only on the ScoreListener interface, so new kinds of listeners need no change to it.
What to say in the interview
"Observer defines a one-to-many dependency: when the subject changes, all subscribed observers are notified automatically. It decouples the subject from the observers, which is the basis of event listeners, UI updates and notification systems."
Common mistakes
- Forgetting to unsubscribe, which keeps old observers alive and receiving events.