Skip to content

Instantly share code, notes, and snippets.

@bitbrain
Created October 7, 2014 14:04
Show Gist options
  • Save bitbrain/a538bf73e85e8c98d7c0 to your computer and use it in GitHub Desktop.
Save bitbrain/a538bf73e85e8c98d7c0 to your computer and use it in GitHub Desktop.
package de.bitbrain.guice;
import java.util.HashMap;
import java.util.Map;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.name.Named;
public class StateHandler {
private Map<Integer, State> states;
private State current;
@Inject @Named("stateScope") StateScope scope;
@Inject
private Injector injector;
public StateHandler() {
states = new HashMap<Integer, State>();
current = null;
}
public void register(int id, Class<? extends State> stateClass) {
scope.enter(stateClass);
states.put(id, injector.getInstance(stateClass));
}
public void setState(Class<? extends State> stateClass) {
scope.leave();
scope.enter(stateClass);
current = injector.getInstance(stateClass);
current.enter();
}
void setState(int id) {
if (current != null) {
scope.leave();
current.leave();
}
current = states.get(id);
if (current != null)
current.enter();
}
public void run() {
if (current != null) {
current.run();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment