I'm refactoring an existing state machine that heavily used case statements and emums. I've broken it down to Events and eventhandler objects, each corresponding to a state machine. The eventHandlers return new Events to propagate through the state machine.
So, my code looks something like this:
public class Event {
//common fields and methods
}
public class SpecificEvent extends Event {
//fields specific to this event
}
public class AnotherEvent extends Event {
//fields specific to this event
}
public class EventHandler {
public Event handleEvent(SpecificEvent evt) {
//do default something
}
public Event handleEvent(AnotherEvent evt) {
//do default something else
}
}
public class StateOneEventHandler extends EventHandler {
public Event handleEvent(SpecificEvent evt) {
//do State1 things
}
public Event handleEvent(AnotherEvent evt) {
//do other State1 things
}
}
public class StateTwoEventHandler extends EventHandler {
public Event handleEvent(SpecificEvent evt) {
//do State2 things
}
public Event handleEvent(AnotherEvent evt) {
//do other State2 things
}
}
My problem and question is: I'm only passing generic Event references around in my state machine, so how can I call the correct handler for an event?
Event evt = new SpecificEvent();
EventHandler handler = new StateOneEventHandler();
//... later
handler.handleEvent(evt); //compiler error
What is the best way of accomplishing this runtime event "dispatch" ?