Skip to content

Observer

  • Is a behavioral pattern
  • Observer defines a one to many dependency so that when one object changes state, all its dependents are notified automatically
  • One object publishes changes, many objects react

Solves

  • Tight coupling
  • Need to explicitly know who all to notify
  • Adding / Removing listeners difficulty
Role Responsibility Analogy
Subject Keeps track of everyone who wants updates. It provides methods to attach() or detach() observers. YouTube Channel: It keeps a list of all its subscribers.
ConcreteSubject The actual object being watched. When its state changes, it sends a "Notify" signal to all observers. The Creator: When they upload a new video, the "Notify" process starts.
Observer An interface that defines the update() method that the Subject will call. The "Notification" Bell: A standard way for any device to receive an alert.
ConcreteObserver The actual object reacting. It implements the update() method to do something specific. Your Phone/Email: One reacts by showing a popup; another reacts by sending an email.

Pasted image 20260211013222.png

interface Observer {
    void update(int temperature);
}

interface Subject {
    void registerObserver(Observer o);
    void removeObserver(Observer o);
    void notifyObservers();
}

class WeatherStation implements Subject {
    private List<Observer> observers = new ArrayList<>();
    private int temperature;

    public void setTemperature(int temp) {
        this.temperature = temp;
        notifyObservers();
    }

    @Override
    public void registerObserver(Observer o) {
        this.observers.add(o);
    }

    @Override
    public void removeObserver(Observer o) {
        this.observers.remove(o);
    }

    @Override
    public void notifyObservers() {
        for (Observer o : observers) {
            o.update(temperature);
        }
    }
}

class PhoneDisplay implements Observer {
    @Override
    public void update(int temperature) {
        System.out.println("updated temp in phone display");
    }
}

class TVDisplay implements Observer {
    @Override
    public void update(int temperature) {
        System.out.println("updated temp in TV display");
    }
}

class Client {
    public static void main(String[] args) {
        WeatherStation station = new WeatherStation();
        Observer phone = new PhoneDisplay();
        Observer tv = new TVDisplay();

        station.registerObserver(phone);
        station.registerObserver(tv);

        station.setTemperature(10);
        station.setTemperature(20);
    }
}