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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| 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
