Concept Explanation
These two solve opposite problems. Observer lets one event notify many listeners without knowing who they are. Decorator wraps an object to add behaviour without touching its class.
Observer
The classic setup: something happens, and several unrelated parts of the system need to react. Hard-coding those reactions makes the publisher depend on all of them.
public interface OrderListener {
void onOrderPlaced(Order order);
}
public class OrderPublisher {
private final List<OrderListener> listeners = new ArrayList<>();
public void subscribe(OrderListener l) { listeners.add(l); }
public void place(Order order) {
save(order);
listeners.forEach(l -> l.onOrderPlaced(order)); // notify everyone
}
}
publisher.subscribe(order -> email.confirm(order));
publisher.subscribe(order -> inventory.reserve(order));
publisher.subscribe(order -> analytics.track(order));
The publisher knows nothing about email, inventory, or analytics. Adding a fourth listener does not modify it.
Spring builds this in:
@Service
public class OrderService {
private final ApplicationEventPublisher events;
public void place(Order order) {
repo.save(order);
events.publishEvent(new OrderPlacedEvent(order));
}
}
@Component
public class EmailListener {
@EventListener
public void on(OrderPlacedEvent e) { email.confirm(e.order()); }
}
Decorator
Adding behaviour by subclassing explodes combinatorially — CachedRepository, LoggedRepository, CachedLoggedRepository, and so on. Decorators compose instead.
public interface DataSource {
String read(String key);
}
public class DatabaseSource implements DataSource {
public String read(String key) { return db.query(key); }
}
// Each decorator wraps another DataSource
public class CachingSource implements DataSource {
private final DataSource inner;
private final Map<String, String> cache = new ConcurrentHashMap<>();
public CachingSource(DataSource inner) { this.inner = inner; }
public String read(String key) {
return cache.computeIfAbsent(key, inner::read);
}
}
public class LoggingSource implements DataSource {
private final DataSource inner;
public LoggingSource(DataSource inner) { this.inner = inner; }
public String read(String key) {
log.info("Reading {}", key);
return inner.read(key);
}
}
DataSource source = new LoggingSource(new CachingSource(new DatabaseSource()));
Three behaviours, three small classes, any combination available — and DatabaseSource never changed.
Java's own IO library is built entirely on this:
new BufferedReader(new InputStreamReader(new FileInputStream("data.txt")));
Common Mistakes
- Exceptions in a listener killing the publisher: One failing listener should not abort the others. Catch per listener.
- Listeners that are never removed: In long-lived publishers this is a memory leak.
- Slow synchronous listeners: They add directly to the publisher's latency. Use
@Asyncwhen the work can wait. - Deep decorator stacks: Six layers make stack traces unreadable. Two or three is usually the practical limit.
Best Practices
- Observer for one-to-many notification where the publisher should not know its audience.
- Decorator for cross-cutting behaviour — caching, logging, retries, metrics.
- Use Spring's event system rather than hand-rolling observer in a Spring app.
- Keep each decorator single-purpose, so they compose cleanly in any order.
Practice Exercises
- The Event Chain: Publish one Spring event and have three listeners react. Confirm the publisher references none of them.
- The Decorator Stack: Wrap a data source in caching and logging decorators and verify the second read hits the cache.
- The Failing Listener: Make one listener throw, and change the publisher so the others still run.