devutility.internal.base.SingletonFactory Maven / Gradle / Ivy
package devutility.internal.base;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import devutility.internal.lang.ClassHelper;
public class SingletonFactory {
/**
* Container for singleton object.
*/
private static volatile ConcurrentMap container = new ConcurrentHashMap<>();
/**
* Get or create a singleton object.
* @param clazz: Class of singleton object.
* @return {@code T}
*/
public static T get(Class clazz) {
String key = clazz.getName();
return get(key, clazz);
}
/**
* Get a singleton object.
* @param key: Key of singleton object to save.
* @param clazz: Class of singleton object.
* @return {@code T}
*/
public static T get(String key, Class clazz) {
if (container.get(key) != null) {
Object value = container.get(key);
if (value != null && value.getClass().isAssignableFrom(clazz)) {
return clazz.cast(value);
}
container.remove(key);
}
return null;
}
/**
* Create a singleton object.
* @param clazz: Class of singleton object.
* @return {@code T}
*/
public static T create(Class clazz) {
String key = clazz.getName();
return create(key, clazz);
}
/**
* Create a singleton object.
* @param key: Key of instance.
* @param clazz: Class of singleton object.
* @return {@code T}
*/
public static T create(String key, Class clazz) {
if (container.get(key) != null) {
Object value = container.get(key);
if (value != null && value.getClass().isAssignableFrom(clazz)) {
return clazz.cast(value);
}
container.remove(key);
}
synchronized (SingletonFactory.class) {
if (container.get(key) == null) {
T value = ClassHelper.instance(clazz);
container.put(key, value);
}
}
return clazz.cast(container.get(key));
}
/**
* Save an instance in container.
* @param key: Key of instance.
* @param instance: Singleton instance.
* @return {@code T}
*/
public static T save(String key, T instance) {
synchronized (SingletonFactory.class) {
container.put(key, instance);
}
return instance;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy