I'm trying to implement the Event Generator Idiom (http://www.javaworld.com/javaworld/jw-09-1998/jw-09-techniques.html). I find things to be a bit "odd" when it comes to the observable class though. Let's say I have the following classes:
interface BakeryListener + orderReceived(BakeryEvent event) + orderProcessing(BakeryEvent event) + orderFinished(BakeryEvent event) + orderDelivered(BakeryEvent event) LogView, OrderReadyView etc. implements BakeryListener Creates a GUI for each own use Order VO / DTO object, used as the source in BakeryEvent BakeryDAO (the observable) - orders : Vector - listeners : Vector + takeOrder, cancelOrder, bake and other regular DAO methods, triggering an event by calling fireEvent + addBakeryListener(BakeryEvent event) + removeBakeryListener(BakeryEvent event) - fireEvent(Order source, EVENTTYPE????) BakeryGUI Creates/gets a reference to BakeryDAO. Creates and attaches LogView, OrderReadyView as listeners on BakeryDAO.
In the link I gave initially he recommends to "Name the event propagator method fire[listener-method-name].". I find this to be redundant: making a snapshot and iterating over the listeners in each fire-method, when the only thing changing is which method to call on the interface. Thus I have made a single fireEvent method, and it is working sort of. The problem is to keep the datatype of the event parameter in fireEvent "in sync" with the methods defined in BakeryListeners. Currently the fireEvent looks like this (excerpt):
for(BakeryListener listener : copyOfListeners){ if(eventType.equals("received")) listener.orderReceived(event); else if(eventType.equals("processing")) listener.orderProcessing(event); }
... etc. I guess I could use an enum instead of a string to make it impossible to call fireEvent with an eventType that doesn't exist, but I still have to map Type.RECEIVED to listener.orderReceived etc?
Is it possible for the fireEvent method to take the BakeryListeners methods as a parameter? I.e (pseudo-code) method declaration:
fireEvent(BakeryListeners.methods eventType, Order source)
and then just call the appropriate method directly inside fireEvent(without if/switching):
call(listener, eventType( source))
Then it also would be impossible to create a event who isn't defined in the interface BakeryDAO.takeOrder() -> fireEvent(eventWhoDoesntExist) -> exception?
Is it possible to do this in Java? Or a better way if I've understood things wrong?