1

I have a situation where objects are created at unpredictable times. Some of these objects are created before an important event, some after. If the event already happened, I make the object execute stuff right away. If the event is forthcoming, I make the object observe the event. When the event triggers, the object is notified and executes the same code.

if (subject.eventAlreadyHappened()) {
    observer.executeStuff();
} else {
    subject.subscribe(observer);
}

Is there another design pattern to wrap or even replace this observer pattern? I think it looks a little dirty to me.

1 Answer 1

4

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.

4
  • For the standard observer pattern, do programmers expect this behavior upon subscription? If not, then should I create two subscription functions - one just like your example, and another to only publish future events?
    – JoJo
    Commented Jun 23, 2012 at 18:36
  • Do you mean that with the standard observer pattern you only want to be notified about events that have occurred after subscription?
    – Giorgio
    Commented Jun 23, 2012 at 20:11
  • I don't know what the standard is. Is the standard to be notified of future events only or is it standard to be notified when someone subscribes late?
    – JoJo
    Commented Jun 23, 2012 at 21:00
  • I honestly do not know if there is such a standard. But I do not think there is anything wrong for an object to generate an event when another object subscribes.
    – Giorgio
    Commented Jun 23, 2012 at 21:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.