以下是我的通用Singleton,它为任何给定的类提供了Singleton对象。基本上是Bill Pugh和Singleton枚举模式的混合体。还能改善吗?请提出建议。
public enum GSingleton {
INSTANCE;
private GSingleton() {
}
private static class SingletonHelper {
private static Map<String, Object> instances = new HashMap<String, Object>();
private static <T> T Instance(Class<T> c) throws InstantiationException, IllegalAccessException {
T newInstance = null;
if (instances.containsKey(c.getName())) {
newInstance = (T) instances.get(c.getName());
} else {
newInstance = c.newInstance();
instances.put(c.getName(), newInstance);
}
return newInstance;
}
}
public static <T> T getInstance(Class<T> c) throws InstantiationException, IllegalAccessException {
synchronized (c) {
return SingletonHelper.Instance(c);
}
}
}