0Pricing
Java Academy · Lesson

Observer Pattern: Event Notification

Implement Observer to decouple event producers from consumers in a stock price system.

Observer Pattern: Event Notification is a free Java Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The Observer Intent

Observer (also called Publish-Subscribe) defines a one-to-many dependency: when the subject changes state, all registered observers are notified automatically.

Subject and Observer Interfaces

The subject tracks a list of observers and notifies them. Observers implement an update method to react to events.

public interface Observer {
    void update(String event, Object data);
}
public interface Subject {
    void addObserver(Observer o);
    void removeObserver(Observer o);
    void notifyObservers(String event, Object data);
}

Concrete Subject: Stock Ticker

The subject holds state and calls notifyObservers whenever the state changes. It manages the observer list.

public class StockTicker implements Subject {
    private final List<Observer> observers = new ArrayList<>();
    private double price;
    public void addObserver(Observer o)    { observers.add(o); }
    public void removeObserver(Observer o) { observers.remove(o); }
    public void setPrice(double p) {
        this.price = p;
        notifyObservers("PRICE_CHANGED", p);
    }
    public void notifyObservers(String ev, Object data) {
        for (Observer o : observers) o.update(ev, data);
    }
}

Concrete Observers

Each observer reacts differently to the same notification. Add observers at runtime without modifying the subject.

public class AlertSystem implements Observer {
    public void update(String ev, Object data) {
        if ((double) data < 100) System.out.println("ALERT: Low price!");
    }
}
public class Logger implements Observer {
    public void update(String ev, Object data) {
        System.out.println("LOG: " + ev + " = " + data);
    }
}

Wiring Observers

Register observers on the subject. They all react when the subject changes. Unregister to stop receiving updates.

StockTicker ticker = new StockTicker();
ticker.addObserver(new AlertSystem());
ticker.addObserver(new Logger());
ticker.setPrice(95.5); // both observers notified

java.util.Observable — Deprecated

The JDK had java.util.Observable and java.util.Observer, but they are deprecated since Java 9. Implement your own or use reactive libraries like RxJava or Project Reactor.

PropertyChangeListener

Java beans provide PropertyChangeSupport — a built-in observer mechanism for bean property changes used heavily in Swing and JavaFX.

public class Model {
    private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);
    private int value;
    public void addPropertyChangeListener(PropertyChangeListener l) { pcs.addPropertyChangeListener(l); }
    public void setValue(int v) {
        int old = this.value; this.value = v;
        pcs.firePropertyChange("value", old, v);
    }
}

Functional Observer with Consumer

Use Consumer<T> as a lightweight observer instead of a dedicated interface — perfect for simple event callbacks.

List<Consumer<Double>> listeners = new ArrayList<>();
listeners.add(p -> { if (p < 100) System.out.println("Low price"); });
listeners.add(p -> System.out.println("Price: " + p));
double newPrice = 95.5;
listeners.forEach(l -> l.accept(newPrice));

Observer vs Event Bus

An event bus (like Guava EventBus) decouples subject and observer further — the subject posts events to the bus without knowing who listens. Observers subscribe by method annotation.

// Guava EventBus example
EventBus bus = new EventBus();
bus.register(new Logger());       // subscribe
bus.post(new PriceEvent(95.5));   // publish

Thread Safety in Observer

If observers can be added/removed from multiple threads, protect the list with synchronized or use CopyOnWriteArrayList for notification-heavy workloads.

private final List<Observer> observers = new CopyOnWriteArrayList<>();

Avoiding Memory Leaks

Strong references in the observer list prevent GC. Use WeakReference<Observer> or always unregister observers when they are no longer needed.

Observer in Real Frameworks

Spring's ApplicationEventPublisher, Android LiveData, and JavaFX properties are all implementations of the Observer pattern at different abstraction levels.

Quick Check

What is the main benefit of the Observer pattern?

Recap

Observer defines a one-to-many notification chain. Implement via interfaces or functional consumers. Use CopyOnWriteArrayList for thread safety and always unregister observers to prevent leaks.

Frequently asked questions

Is the “Observer Pattern: Event Notification” lesson free?

Yes — the full text of “Observer Pattern: Event Notification” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.

What will I learn in “Observer Pattern: Event Notification”?

Implement Observer to decouple event producers from consumers in a stock price system. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Observer Pattern: Event Notification” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Observer Pattern: Event Notification
  2. Strategy Pattern: Interchangeable Algorithms
  3. Command Pattern: Encapsulating Actions
  4. Template Method: Defining Algorithm Skeletons
← Back to Java Academy