Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
π§ What Is the Observer Pattern?
The Observer Pattern is a behavioral design pattern where:
- A Subject (Observable) maintains a list of Observers.
- When the Subjectβs state changes, all registered Observers are notified.
- Promotes loose coupling between the Subject and Observers.
π¦ Real-World Use Cases
Use Case | Description |
---|---|
π° News Feed Subscription | Readers get notified of new articles |
π¬ Chat App (Message Stream) | Chat UI observes incoming message stream |
π² Event Bus / Pub-Sub | Listeners get notified of published events |
π Live Data Dashboard | Charts observe backend data updates |
π¦ Weather Monitoring App | UI gets updates when weather data changes |
π§ͺ JUnit / Test Listeners | Hooks triggered when test results change |
π§ When to Use
β Use when:
- You want to decouple state producer from state consumers
- Many objects need to react to changes in a shared object
- You want to implement event-driven behavior cleanly
π UML Diagram
+---------------------+ +--------------------+
| Subject |<>------->| Observer |
+---------------------+ +--------------------+
| +attach(obs) | | +update() |
| +detach(obs) | +--------------------+
| +notifyObservers() |
+---------------------+
β²
|
+-------------------------+
| ConcreteSubject |
+-------------------------+
| - state |
| +getState(), setState() |
+-------------------------+
β²
|
+-------------------------+
| ConcreteObserver |
+-------------------------+
| - name |
| - subject ref |
| +update() |
+-------------------------+
π» Java Implementation β Weather Monitoring Example
β
Observer.java
public interface Observer {
void update(String temperature);
}
β
Subject.java
public interface Subject {
void attach(Observer observer);
void detach(Observer observer);
void notifyObservers();
}
β
WeatherStation.java
(Concrete Subject)
public class WeatherStation implements Subject {
private String temperature;
private final List<Observer> observers = new ArrayList<>();
public void setTemperature(String temp) {
this.temperature = temp;
notifyObservers();
}
public String getTemperature() {
return temperature;
}
@Override
public void attach(Observer observer) {
observers.add(observer);
}
@Override
public void detach(Observer observer) {
observers.remove(observer);
}
@Override
public void notifyObservers() {
for (Observer o : observers) {
o.update(temperature);
}
}
}
β
WeatherDisplay.java
(Concrete Observer)
public class WeatherDisplay implements Observer {
private final String displayId;
public WeatherDisplay(String displayId) {
this.displayId = displayId;
}
@Override
public void update(String temperature) {
System.out.println("πΊ Display [" + displayId + "] - Temp Updated: " + temperature);
}
}
β
Client.java
public class ObserverDemo {
public static void main(String[] args) {
WeatherStation station = new WeatherStation();
WeatherDisplay display1 = new WeatherDisplay("Lobby");
WeatherDisplay display2 = new WeatherDisplay("Office");
station.attach(display1);
station.attach(display2);
station.setTemperature("25Β°C");
station.setTemperature("28Β°C");
station.detach(display1);
station.setTemperature("30Β°C");
}
}
π§ͺ Output
πΊ Display [Lobby] - Temp Updated: 25Β°C
πΊ Display [Office] - Temp Updated: 25Β°C
πΊ Display [Lobby] - Temp Updated: 28Β°C
πΊ Display [Office] - Temp Updated: 28Β°C
πΊ Display [Office] - Temp Updated: 30Β°C
β¨ Benefits
Feature | Description |
---|---|
β Loose coupling | Subject doesnβt need to know concrete observers |
β Scalability | Can add/remove observers at runtime |
β Reactive systems | Ideal for implementing event-driven behavior |
β Open/Closed | Add new observers without modifying subject |
β οΈ Limitations
- β Notification order is not guaranteed
- π§© Potential performance hit if observer list is large
- β οΈ Risk of memory leaks if observers are not detached properly
π§Ύ Summary
Key Point | Value |
---|---|
Pattern Type | Behavioral |
Participants | Subject, Observer, ConcreteObserver |
Key Use Case | Push-based event propagation |
Real Java Example |
java.util.Observable (deprecated), Spring ApplicationEventPublisher , RxJava, Akka |
π§ Interview Tip
When asked to design a notification system, event bus, or data feed, use the Observer Pattern.
You can also mention:
- β Kafka (pub-sub variation)
- β RxJava / Project Reactor (reactive observers)
- β Spring Events (Observer abstraction)
Top comments (0)