Observer
- Java course
- Advanced
- Lesson 40/82
- 5 min
Learn the Observer pattern.
The Observer pattern
The Observer lets an object notify its subscribers about state changes. The notifier is called the Subject, the receivers are Observers. This is a publish-subscribe relationship.
Example: when a temperature sensor (Subject) changes, a screen and a log (Observers) are informed. The Subject adds subscribers with attach and calls update on all of them with broadcast. Subscribers can be added at any time, keeping parts of the system independent.
Registration and notification flow
Observers are registered into a list with attach. When a change happens the Subject walks this list and calls update on each. The notification can carry a string or an object.
In Java a List<Observer> usually holds the subscribers. With many subscribers the order matters, so registration order is preserved. A detach method can be added to unsubscribe.
Practice Notify sensor subscribers
Define an Observer interface with void update(String msg). A Screen class implements it and prints "screen: " + msg with System.out.println inside update. A Subject class has attach(Observer) and broadcast(String msg) methods; broadcast calls update on every Observer in the list. In main, attach a Screen and call broadcast("temp 30").
Starter code
// Define the Observer interface and Screen class
// Add attach to the Subject class
// Call broadcast in mainSample solution
import java.util.*;
interface Observer { void update(String msg); }
class Screen implements Observer {
public void update(String msg) { System.out.println("screen: " + msg); }
}
class Subject {
private List<Observer> list = new ArrayList<>();
public void attach(Observer o) { list.add(o); }
public void broadcast(String msg) { for (Observer o : list) o.update(msg); }
}
public class ObserverDemo {
public static void main(String[] args) {
Subject s = new Subject();
s.attach(new Screen());
s.broadcast("temp 30");
}
}Expected output
screen: temp 30
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the Observer roles
| Term | Meaning |
|---|---|
Subject |
Sends notifications |
Observer |
Receives notifications |
attach |
Adds a subscriber |
update |
Notification method |
2 Complete the attach call
subject.____(new Screen());
subject.attach(new Screen());
Explanation: attach adds a new subscriber.
3 Who notifies the subscribers in the Observer pattern?
- Observer
- The interface
- Decorator
- Subject Correct answer
Explanation: The Subject sends notifications to subscribed Observers.