All topics
library
intermediate

Observer Pattern & Event Handling

Implement publish-subscribe in Java using listeners, PropertyChangeSupport, or modern reactive alternatives.

The Observer pattern lets objects (observers/listeners) subscribe to events from a subject (publisher). When the subject's state changes, all observers are notified.

Observer = a newsletter subscription. You subscribe (register). When the publisher has news (state change), all subscribers receive the update. You can unsubscribe anytime. The publisher doesn't need to know who you are — just that you're on the list.

Key Concepts

1
Java implementations:
2
1. Custom listeners (most common): - Define a listener interface - Subject maintains a List<Listener> - Subject calls listener methods on state change - Thread-safe with CopyOnWriteArrayList
3
2. PropertyChangeSupport (JavaBeans): - Built-in support for property change events - addPropertyChangeListener() / firePropertyChange() - Each event carries old and new values
4
3. java.util.Observer/Observable (deprecated since Java 9): - Don't use — poor design (Observable is a class, not interface)
5
4. Modern alternatives: - Spring ApplicationEventPublisher: type-safe events with @EventListener - Project Reactor / RxJava: reactive streams with backpressure - CompletableFuture: for async one-time notifications
6
Event handling best practices: - Use weak references to avoid memory leaks (observer holds reference to subject) - Notify asynchronously if listeners do heavy work - Define clear event types (not generic 'update' calls) - Allow unsubscribe — prevent leaks in long-running applications