I have a listener class that accepts GUI change events in one method.
The incoming event objects have a superclass of a type of GUI Event, the behaviour should depend on the dynamic type of the incoming variable.
I wanted to do do lots of methods like:
handleGUIEvent(EventChangedX event)
handleGUIEvent(EventChangedY event)
I am using a single event listener and receiving objects of various types but the behaviour should be different for each. What would you do?
I do not want to use a switch statement as this would get unmaintainable.
GUIEventshould provide an abstract method of the typeEach subclass should then implement this method, and call back on a particular method on
EventListener. That way the subclasses ofGUIEventcan determine what to call onEventListener, and the two object classes between them can determine what action to perform. This is known as double-dispatch. It avoidsswitchstatements and the like.Although I’ve drawn this out as EventListener calling on GUIEvent.delegateEvent and calling back on EventListener, there’s no reason why there couldn’t be a third class (say,
EventReceiver). So the abstract method onGUIEventwould look like:and
EventReceiverwould implement appropriate methods to be called by theGUIEvents.