Java › Design Patterns in Java
How would you implement the Observer pattern in Java, and how does it compare to using the built-in PropertyChangeSupport or a reactive streams library?
AdvancedAnswer
The Observer pattern defines a one-to-many dependency where a subject notifies registered observers of state changes -- implementable manually with a List<Observer> and a notify loop, via the JDK's built-in (though somewhat dated) java.beans.PropertyChangeSupport for JavaBean-style property change notification, or more robustly via a reactive streams library (like RxJava or Project Reactor) providing composable operators (filtering, mapping, backpressure handling) far beyond a simple manual observer list, making the choice largely dependent on whether you need simple notification or a full reactive pipeline with transformation and backpressure semantics.
public interface Observer { void update(String event); }
public class EventPublisher {
private final List<Observer> observers = new ArrayList<>();
public void subscribe(Observer o) { observers.add(o); }
public void publish(String event) {
for (Observer o : observers) { o.update(event); }
}
}
EventPublisher publisher = new EventPublisher();
publisher.subscribe(event -> System.out.println("Received: " + event));
publisher.publish("orderPlaced");Real-world example A simple in-process event bus used to decouple order processing from notification/logging concerns implements a lightweight manual Observer pattern (since the use case doesn't need reactive streams' backpressure or complex operator chains), while a data pipeline handling high-volume, filtered, transformed event streams instead adopts Project Reactor for its much richer composability.