devutility.internal.base.SingletonFactory Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of devutility.internal Show documentation
Show all versions of devutility.internal Show documentation
Some utilities for Java development
package devutility.internal.base;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import devutility.internal.lang.ClassUtils;
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 && clazz.isAssignableFrom(value.getClass())) {
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 = ClassUtils.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;
}
}