In one of my java projects I use singletons a lot and I was looking for a way to reduce repeating code. I made a SingletonUtils
class that accepts a class and supplier parameter. Then stores the instance in a hash map. This way the static instance isn't stored as a static variable in the class I want to make a singleton.
My question is, is there any problems/cons with implementing the singleton pattern like this and is there an easier way to do this or is this the best way?
public class SingletonUtils {
public static HashMap<Class, Object> instances = new HashMap<>();
public static <T> T getInstance(final Class<T> singletonObj, final Supplier<T> creator) {
if(!instances.containsKey(singletonObj)) {
if(creator == null) return null;
else instances.put(singletonObj, creator.get());
}
return (T) instances.get(singletonObj);
}
public static boolean instanceExists(final Class singletonObj) {
return instances.containsKey(singletonObj);
}
public static void removeInstance(final Class singletonObj) {
instances.remove(singletonObj);
}
}
public final class AuthManager {
private AuthManager() { }
public static AuthManager getNewInstance() {
return SingletonUtils.getInstance(AuthManager.class, AuthManager::new);
}
}