When building an Observer pattern, you need to define your events that the are broadcast and observed. Is it better to define an abstract Event
class with multiple subclasses for each event, or to define a single enum, where each event is listed in the enum?
option 1:
public abstract class Event { }
public UserInputEvent extends Event {}
public NetwortkEvent extends Event{}
option 2:
public enum Event {
USER_INPUT_EVENT,
NETWORK_EVENT
}
I've seen examples of both:
- using class: https://blog.kaush.co/2014/12/24/implementing-an-event-bus-with-rxjava-rxbus/
- using enum: https://juanchopanzacpp.wordpress.com/2013/02/24/simple-observer-pattern-implementation-c11/
I'm leaning towards option 2. A lot of my decision is based on the fact that I'm working in java, so this might be different for different languages:
- option 1 will require lots of
if X instanceOf Y
checks which looks ugly. - option 2 will allow clean
switch
statements - option 2 will list all possible events nicely in one location. I know most IDEs can show all subclasses of a class but this is less obvious.
- option 1 doesn't restrict the addition of more subclasses. If you are writing a library, any user of the library can subclass
Event
and clutter the code with more events. option 2 fixes the number of events until someone actually updates the enum - option 1 allows for sub-sub events, which may be good or bad. (e.g.
public TouchUserInputEvent extends UserInputEvent {}
- option 1 allows you to attach additional meta data to the event. IMO this can lead to cluttered code if your goal is simplicity.
as an example:
public UserInputEvent extends Event {
int xLocation;
int yLocation;
}
UPDATE: I ended up going with option 1. I did have a need to include additional data in the event and using a class was the only way to go. Plush @whatsisname was right, having to re-fetch the updated event data would be callback hell.