I need to implement classes to support a custom event capable of passing varying types/amounts of data based on the event type. For example,
With event Type A I need to pass 2 String names.
With event Type B I need to pass 3 String names and a double.
2 designs I’ve found:
-
An extension of EventObject that contains fields and methods for all of possible data (fields not required for some event types are left blank).
// event constructors public MyEvent(Object source, int type, String a, String b) {} public MyEvent(Object source, int type, String a, String b, String c, double d) {} -
An extension of EventObject that contains a parameter for an EventInfo object. EventInfo is a base class for change info. Methods firing specific events will pass along subclasses of EventInfo containing the necessary change information (listeners would be required to downcast).
// event constructors public MyEvent(Object source, int type, EventInfo info) {} // base class for event info public class EventInfo {}
What other designs exist for implementing this? What are the pros and cons of each?
Thanks.
One common design would be to include a Map in your event class to keep parameters as well as a field to show the event type. Your event interface would therefore look like this:
In your event handler class you can use getParameter() and getType() to retrieve the event’s parameters and event type.