Question

Suppose I have:

class Event {}
class DoorBell extends Event {}
class PhoneCall extends Event {}
class EventGenerator {
    static Event getEvent() {
         if (today.isSunday())
            return new DoorBell()
         else 
            return new PhoneCall();
    }
}
class EventHandler {    
    void HandleEvent(DoorBell doorBell) { answer door; }
    void HandleEvent(PhoneCall phoneCall) { answer phone; }
    void consumeEvent() {
         Event e = EventGenerator.getEvent();
         HandleEvent(e);
    }
}

HandleEvent(e) doesn't compile since HandleEvent(Event) is undefined. Is there a solution for this? Or do I have to ask e what kind of event it is?

Was it helpful?

Solution

The usual idiom would be to pass an Event and let polymorphism handle it all for you.

I see no value in your EventHandler class without any behavior. Your design, as posed, offers no polymorphic benefit. That's the reason you have to check types. Better to have something like this:

public interface EventHandler {
    void handle(Event event);
}

The Visitor pattern (aka "double dispatch") can be a good way to handle this situation.

Or you can try generics:

public class EventHandler {
   public <T> void consumeEvent(T event) {
       // handler code here, dependent on T
   }
}

I don't know if JDK 7 has something new to help you out. Sorry; I'm still stuck on JDK 6.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top