Skip to content

Instantly share code, notes, and snippets.

@StanKocken
Last active November 7, 2015 11:14
Show Gist options
  • Save StanKocken/39d604bcf8c814a48859 to your computer and use it in GitHub Desktop.
Save StanKocken/39d604bcf8c814a48859 to your computer and use it in GitHub Desktop.
A singleton pattern, to make the Mock of it easily
public class MyManager {
private MyManager() {}
public static MyManager getInstance() {

return Singleton.getInstance(MyManager.class);

}
public void myMethod() {
}
}
public class Singleton {
private static final Map<Class, Object> SINGLETONS = new HashMap<>();
private Singleton() { }
public static synchronized <T> T getInstance(Class<T> clazz) {
T instance = (T) SINGLETONS.get(clazz);
if (instance == null) {
try {
instance = createInstance(clazz);
setInstance(clazz, instance);
} catch (Exception e) {
VLog.e(e);
}
}
return instance;
}
public static <T> void setInstance(Class<T> clazz, T instance) {
SINGLETONS.put(clazz, instance);
}
public static void clear() {
SINGLETONS.clear();
}
@NonNull
private static <T> T createInstance(Class<T> clazz)
throws IllegalAccessException, NoSuchMethodException,
InstantiationException, InvocationTargetException {
Constructor<T> constructor = clazz.getDeclaredConstructor();
constructor.setAccessible(true);
return constructor.newInstance();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment