Implement Observer-style notification in Java by making subject responsibilities, listener contracts, and event semantics explicit.
Observer: A pattern where one subject publishes changes and multiple observers react without the subject hard-coding each reaction path.
In modern Java, the simplest form still looks familiar:
1public interface InventoryListener {
2 void inventoryChanged(InventoryEvent event);
3}
1public final class InventorySubject {
2 private final List<InventoryListener> listeners = new ArrayList<>();
3
4 public void addListener(InventoryListener listener) {
5 listeners.add(listener);
6 }
7
8 public void updateStock(String sku, int quantity) {
9 InventoryEvent event = new InventoryEvent(sku, quantity);
10 listeners.forEach(listener -> listener.inventoryChanged(event));
11 }
12}
The key design work is not the list of listeners. It is:
If one listener fails, should others still run? If events are synchronous, what latency is the subject now exposed to? Those are design decisions, not implementation details.