Skip to content

Instantly share code, notes, and snippets.

@grignaak
Created February 22, 2011 20:16
Show Gist options
  • Save grignaak/839295 to your computer and use it in GitHub Desktop.
Save grignaak/839295 to your computer and use it in GitHub Desktop.
Singleton to end all singletons
package common;
import java.util.HashMap;
import java.util.Map;
public class Global {
private static boolean inTests;
private static final Map<Class<?>, Object> globals = new HashMap<Class<?>, Object>();
private Global() {}
public static <T> void initializeInstance(Class<T> type, T global) {
if (globals.containsKey(type) && !inTests)
throw new IllegalArgumentException("This global is already initialized:" + type);
globals.put(type, global);
}
public static <T> T getInstance(Class<T> type) {
if (!globals.containsKey(type))
throw new IllegalArgumentException("Not a global: " + type);
return type.cast(globals.get(type));
}
public static void ISolemnlySwearIAmInATest() {
inTests = true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment