Posts

Showing posts from November 17, 2018

Storing singleton instances in a generic utils class

Image
up vote 0 down vote favorite 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;