Skip to content

Instantly share code, notes, and snippets.

@benbor
Created September 11, 2017 21:03
Show Gist options
  • Save benbor/750a910344ee8d36baf8a6ff272996bb to your computer and use it in GitHub Desktop.
Save benbor/750a910344ee8d36baf8a6ff272996bb to your computer and use it in GitHub Desktop.
package rocks.biankouski.runinfiregame.desktop.opengl.service;
import java.util.Hashtable;
import java.util.Map;
public class DI {
private final Map<Class<?>, Initializable> callbacks = new Hashtable<>();
private final Map<Class<?>, Object> initiated = new Hashtable<>();
public interface Initializable {
Object init(DI di) throws NotDeclaredException;
}
public class NotDeclaredException extends Exception {
NotDeclaredException(String message) {
super(message);
}
}
public void share(Class cls, Initializable callback) {
callbacks.put(cls, callback);
}
public Object get(Class className) throws NotDeclaredException {
Object instance = initiated.get(className);
if (instance != null) {
return instance;
}
Initializable initializable = callbacks.get(className);
if (initializable == null) {
throw new NotDeclaredException(className.getName() + " wasn't declared.");
}
instance = initializable.init(this);
initiated.put(className, instance);
return instance;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment