Created
February 22, 2011 20:16
-
-
Save grignaak/839295 to your computer and use it in GitHub Desktop.
Singleton to end all singletons
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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