提交 502366bb 编写于 作者: G guide

[fix]单例对象的工厂类

上级 dc3806ca
......@@ -11,30 +11,25 @@ import java.util.Map;
* @createTime 2020年06月03日 15:04:00
*/
public final class SingletonFactory {
private static volatile Map<String, Object> objectMap = new HashMap<>();
private static final Map<String, Object> OBJECT_MAP = new HashMap<>();
private SingletonFactory() {
}
public static <T> T getInstance(Class<T> c) {
String key = c.toString();
Object instance = objectMap.get(key);
if (instance == null) {
synchronized (SingletonFactory.class) {
instance = objectMap.get(key);
if (instance == null) {
try {
instance = c.getDeclaredConstructor().newInstance();
objectMap.put(key, instance);
} catch (IllegalAccessException | InstantiationException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (NoSuchMethodException | InvocationTargetException e) {
e.printStackTrace();
}
Object instance;
synchronized (SingletonFactory.class) {
instance = OBJECT_MAP.get(key);
if (instance == null) {
try {
instance = c.getDeclaredConstructor().newInstance();
OBJECT_MAP.put(key, instance);
} catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
}
return c.cast(instance);
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册