Behavioral Design Pattern
Observer Design Pattern in Java
Notify dependent objects automatically when a subject's state changes.
In this lesson: Observer defines a one-to-many relationship. When a subject changes, it publishes an event to registered observers.
Overview
Observer is useful when its recurring design problem appears in a real application. It keeps the relevant responsibilities organized while allowing surrounding code to depend on clear abstractions.
Implementation
interface Observer { void update(String value); }
final class Dashboard implements Observer { public void update(String value) { System.out.println("Updated: " + value); } }
final class Subject { private final List<Observer> observers = new ArrayList<>(); void subscribe(Observer observer) { observers.add(observer); } void publish(String value) { observers.forEach(observer -> observer.update(value)); } }
Subject subject = new Subject();
subject.subscribe(new Dashboard());
subject.publish("READY");
When should you use it?
Use Observer for event notifications, dashboards, domain events, UI updates, and subscribers that should react to a state change.
Next step: Continue with the Design Patterns course and explore the next pattern.