使用Enum和billpugh方法的java通用单例
下面是我的通用Singleton,它为任何给定类提供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);
}
}
}
共 (0) 个答案