Observer

Notify Many Listeners

Observer (publish–subscribe): a subject keeps a list of listeners and notifies all of them when something happens. The subject does not know what the listeners do, so new features (SMS, analytics, loyalty points) plug in without changing the order code.

Example

import java.util.*;
import java.util.function.Consumer;

public class Main {
    public static void main(String[] args) {
        EventBus<OrderPlaced> bus = new EventBus<>();
        bus.subscribe(e -> System.out.println("[Email]     Receipt sent for " + e.orderId()));
        bus.subscribe(e -> System.out.println("[Inventory] Reserved stock for " + e.orderId()));
        bus.subscribe(e -> System.out.println("[Loyalty]   +" + e.amount() / 100 + " points to " + e.customer()));

        bus.publish(new OrderPlaced("ORD-1", "ravi", 2499));
        bus.publish(new OrderPlaced("ORD-2", "anita", 799));
    }
}

record OrderPlaced(String orderId, String customer, int amount) {}

class EventBus<E> {
    private final List<Consumer<E>> listeners = new java.util.concurrent.CopyOnWriteArrayList<>();
    void subscribe(Consumer<E> listener) { listeners.add(listener); }
    void publish(E event) { listeners.forEach(l -> l.accept(event)); }
}

Output

[Email]     Receipt sent for ORD-1
[Inventory] Reserved stock for ORD-1
[Loyalty]   +24 points to ravi
[Email]     Receipt sent for ORD-2
[Inventory] Reserved stock for ORD-2
[Loyalty]   +7 points to anita

Where You See It

  • Spring: ApplicationEventPublisher.publishEvent(...) + @EventListener / @TransactionalEventListener.
  • GUI and Android: click listeners, LiveData/StateFlow observers.
  • Across services the same idea becomes a message broker: Kafka topics, RabbitMQ exchanges.