Cheatsheet
Observer
Intent
Define a one-to-many dependency so that when one object changes, everyone interested hears about it without that object knowing them.
Structure (UML)
classDiagram
direction LR
class ResultService {
<<ConcreteSubject>>
+record(LiftResult r) boolean
}
class ApplicationEventPublisher {
<<Subject>>
+publishEvent(event)
}
class NotificationListener {
<<ConcreteObserver>>
+on(PersonalRecordEvent e)
}
class LeaderboardListener {
<<ConcreteObserver>>
+on(PersonalRecordEvent e)
}
class BadgeListener {
<<ConcreteObserver>>
+on(PersonalRecordEvent e)
}
ResultService --> ApplicationEventPublisher
ApplicationEventPublisher ..> NotificationListener : notifies
ApplicationEventPublisher ..> LeaderboardListener : notifies
ApplicationEventPublisher ..> BadgeListener : notifiesParticipants
- Subject (ResultService, or ManualPrSubject in the hand-written version), which detects the change and announces it
- Observer (PrObserver, or any @EventListener method), the contract for whoever wants to hear about it
- ConcreteObserver (NotificationListener, LeaderboardListener, BadgeListener), each reacting its own way
- Event (PersonalRecordEvent), what travels from one to the others
ResultService.java
public boolean record(LiftResult r) {
Integer previous = keepBest(r);
boolean pr = previous == null || r.kg() > previous;
if (pr) {
// announce it and move on: who reacts is none of this class's business
events.publishEvent(new PersonalRecordEvent(r.athlete(), r.lift(), r.kg(), previous));
}
return pr;
}Pros
- The service doesn't know who listens, so adding a reaction doesn't touch it
- Each reaction lives in its own class and is tested on its own
- With @Async, slow reactions don't hold up the publisher
Cons
- The flow is harder to follow, because the call no longer shows in the code
- Everything is synchronous by default and a listener's exception reaches the publisher
- Order between listeners isn't guaranteed unless you set it with @Order