Observer Design Pattern in Java

When one object changes, all objects that subscribed to it are told automatically.

Real life example

YouTube: when a channel uploads a video, all subscribers get a notification.

When to use

One change must update many other objects, and you do not want them tightly connected.

Complete Java example

Save this as Main.java, then run javac Main.java and java Main.

import java.util.*;

public class Main {
    public static void main(String[] args) {
        NewsChannel channel = new NewsChannel();
        channel.subscribe(new Reader("Ram"));
        channel.subscribe(new Reader("Sita"));
        channel.publish("Breaking news!");                 // Ram and Sita both get it
    }
}

interface Observer { void update(String news); }

class NewsChannel {                                // the subject
    private List<Observer> subscribers = new ArrayList<>();
    void subscribe(Observer o) { subscribers.add(o); }
    void publish(String news) {
        for (Observer o : subscribers) o.update(news);   // tell everyone
    }
}

class Reader implements Observer {
    private String name;
    Reader(String name) { this.name = name; }
    public void update(String news) { System.out.println(name + " read: " + news); }
}

Output

Ram read: Breaking news!
Sita read: Breaking news!