Cleanly handling events

Posted by nkr1pt on Stack Overflow See other posts from Stack Overflow or by nkr1pt
Published on 2010-04-18T15:39:48Z Indexed on 2010/04/18 15:43 UTC
Read the original article Hit count: 285

Filed under:
|
|

I have code similar to this in all my observer classes that handle events fired by an event bus class. As you can see there are a lot of instanceof checks to choose the path of action needed to appropriately handle events, and I was wondering if this could be done more cleanly, eliminating the instanceof tests?

@Override
public void handleEvent(Event event) {
    if (event instanceof DownloadStartedEvent) {
        DownloadStartedEvent dsEvent = (DownloadStartedEvent)event;
        dsEvent.getDownloadCandidateItem().setState(new BusyDownloadingState());
    } else if (event instanceof DownloadCompletedEvent) {
        DownloadCompletedEvent dcEvent = (DownloadCompletedEvent)event;
        dcEvent.getDownloadCandidateItem().setState(new FinishedDownloadingState());
        DownloadCandidate downloadCandidate = dcEvent.getDownloadCandidateItem(). getDownloadCandidate();
        if (downloadCandidate.isComplete()) {
            // start extracting
        }
    } else if (event instanceof DownloadFailedEvent) {
        DownloadFailedEvent dfEvent = (DownloadFailedEvent)event;
        dfEvent.getDownloadCandidateItem().setState(new FailedDownloadingState());
    }
}

© Stack Overflow or respective owner

Related posts about java

Related posts about events