An alternative would be as follows.
Observers are notified of the event through the method
// Method on all observers.
void notify(Event event)
All new objects are subscribed to the notification, so the subject, instead
of
if (subject.eventAlreadyHappened()) {
observer.executeStuff();
} else {
subject.subscribe(observer);
}
does simply
subject.subscribe(observer);
When the event occurs, the subscribed observer are notified, and the event is cached:
// Method on subject.
void handleEvent(Event event)
{
// lastEvent is a member variable of subject.
lastEvent = event;
...
for (Observer observer : subscribedObservers())
{
observer.notify(event);
}
}
When a new object is subscribed, it is notified immediately if the event
has occurred already:
// Method on subject.
void subscribe(Observer observer)
{
// Add observer to list.
...
if (lastEvent != null)
{
observer.notify(lastEvent);
}
}
Finally, the observer has a method notify:
// Method on observer.
void notify(Event event)
{
executeStuff();
}
So basically the difference is that the subject immediately sends
a notification to a newly subscribed object if at the moment of subscription
the event has already occurred.
I hope this helps.