Java Omnibus
OOAD & Architecture / GoF patterns / Behavioral / Observer Pattern in Java
GoF Behavioral Java Order Management
GoF Pattern

Observer helps when one object’s state change should notify interested listeners without hard-wiring every dependent relationship.

Define a one-to-many dependency so when one object changes state, all its dependents are notified and updated automatically.

Intent

What the pattern is trying to do

Define a one-to-many dependency so when one object changes state, all its dependents are notified and updated automatically.

Problem

What force creates the need

Many interested parties need notification when something happens, but direct coupling between source and every dependent makes the design brittle.

Solution

How the pattern responds

Let observers subscribe to a subject so notifications can fan out through a stable contract.

Structure

How the moving parts fit together

A subject keeps a list of observers and broadcasts events or updates through a shared callback interface.

Java Example

Java example in the Order Management domain

Observer Pattern in Java example
package org.javaomnibus.ecommerce.gof.behavioral;

public interface OrderObserver {
    void onOrderConfirmed(Order order);
}

public final class OrderConfirmedPublisher {
    private final java.util.List observers = new java.util.ArrayList<>();

    public void register(OrderObserver observer) {
        observers.add(observer);
    }

    public void publish(Order order) {
        for (OrderObserver observer : observers) {
            observer.onOrderConfirmed(order);
        }
    }
}
Code Walkthrough

Step by step

  1. Publishers do not need deep knowledge of each observer implementation.
  2. Observers can be added or removed with less coupling to the source.
  3. This fits notification-style relationships more than central orchestration.
  4. Observer is often the gateway into event-driven design thinking.
When To Use

Where this pattern helps

  • When many listeners react to one event source
  • When notification relationships should stay decoupled and extensible
When Not To Use

When a simpler design is better

  • When the source needs fine-grained control over the entire workflow
  • When event fan-out would make behavior too implicit or difficult to trace
Trade-Offs

What this pattern costs

  • Event-driven updates can make execution flow less explicit
  • Ordering, retries, and failure handling require careful design as the system grows
Modern Relevance

How this fits today

Observer remains deeply relevant in Java for domain events, UI listeners, integration hooks, and event-driven processing models.

Common Misuse

Where teams get it wrong

Using Observer when the business flow really needs centralized coordination can create hidden logic scattered across listeners.

Related Patterns

Compare with nearby choices


What To Read Next