Skip to main content

What is the essence of the Observer pattern?

The essence of the Observer pattern is to organize automatic notification of a group of objects (observers) that the state of another object (the publisher) has changed, without a rigid link between them.


1. The Main Idea

When one object (the publisher) changes, it doesn't notify each subscriber directly, it simply broadcasts a notification through a shared mechanism.

Subscribers (observers) decide for themselves how to react to these changes.

In other words: "When something happens, everyone who cares finds out about it automatically."


2. Roles in the Pattern

  • Subject - the object that keeps the list of subscribers and notifies them of changes.
  • Observer - the object that subscribes to events and reacts when it receives them.
  • ConcreteSubject / ConcreteObserver - specific implementations of these roles.

3. Example (Java)

java
// Observer interface interface Observer { void update(String event); } // Publisher class NewsAgency { private List<Observer> observers = new ArrayList<>(); public void subscribe(Observer o) { observers.add(o); } public void unsubscribe(Observer o) { observers.remove(o); } public void notifyObservers(String news) { for (Observer o : observers) o.update(news); } } // Concrete observers class NewsChannel implements Observer { private String name; public NewsChannel(String name) { this.name = name; } public void update(String news) { System.out.println(name + " received news: " + news); } }

Usage:

java
NewsAgency agency = new NewsAgency(); Observer cnn = new NewsChannel("CNN"); Observer bbc = new NewsChannel("BBC"); agency.subscribe(cnn); agency.subscribe(bbc); agency.notifyObservers("A new news bulletin!");

4. Advantages

  • Weaker coupling between the publisher and the subscribers. The publisher doesn't know exactly who is listening to it, only that they implement a common interface.
  • Flexibility - subscribers can be added, removed, and changed at runtime.
  • Easy to extend the event system (new notification types, new reactions).

5. Disadvantages

  • A possible avalanche of notifications if there are many subscribers.
  • Harder to trace the source of a change - events happen "implicitly".

Conclusion

The Observer pattern is needed when one change should automatically trigger a reaction in other parts of the system, but without a direct dependency between them.

Summary:

Observer is a "subscription mechanism" that makes the system event-driven, flexible, and reactive: one reports, the rest react.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.