Video in progress

How does the Observer pattern work? Give a real-life example.

When one object (the subject) changes, the other objects subscribed to it (the observers) get notified automatically. The subject doesn't know them specifically: it just tells each one on the list "something happened".

📖 Answer

A Telegram channel is a good example: the channel posts, the subscribers get the message. The channel doesn't deal with each subscriber individually.

In code:

interface OrderListener {
    void onPaid(Order order);
}

class OrderService {
    private final List<OrderListener> listeners = new ArrayList<>();

    void subscribe(OrderListener l) { listeners.add(l); }

    void markPaid(Order order) {
        order.setStatus(PAID);
        listeners.forEach(l -> l.onPaid(order));
    }
}

service.subscribe(o -> mailer.sendReceipt(o));
service.subscribe(o -> warehouse.reserve(o));

OrderService now knows nothing about mail or the warehouse. If you need a new reaction, you add a new listener.

Spring has a ready-made version of this: ApplicationEventPublisher and @EventListener. The addEventListener on the frontend is the same idea.