Hey guys me again,
I have been having some issues with maintaining my slick2D game in regards to notifying other areas of code something has happened. My solution was to create EventBus essentially a very simple version of the GWT version (I work with it at work so to me its second nature).
The code looks as follows:
package uk.co.digitaldragonstudios.engine.events;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class EventBus {
private static EventBus eventBus;
private Map<EventType,List<Listener<Event>>> bus =
new HashMap<EventType,List<Listener<Event>>>();
public static EventBus get() {
if(eventBus == null) {
eventBus = new EventBus();
}
return eventBus;
}
public void addListener(EventType type,Listener<Event> event) {
if(bus.get(type) != null) {
bus.get(type).add(event);
}
else {
List<Listener<Event>> listeners = new ArrayList<Listener<Event>>();
listeners.add(event);
bus.put(type, listeners);
}
}
public boolean fireEvent(EventType type,Event event) {
if(bus.get(type) != null) {
List<Listener<Event>> listeners = bus.get(type);
for(Listener<Event> listener : listeners) {
listener.onEvent(event);
if(event.isCancelled()) {
return false;
}
}
return true;
}
return false;
}
}
My questions are, is there a better way to do it than this and should it be done in games?
i understand it would never work for Java 4k of course