Skip to content

Instantly share code, notes, and snippets.

@benbor benbor/DI.java
Created Sep 11, 2017

Embed
What would you like to do?
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
You can’t perform that action at this time.