未验证 提交 da6be9d4 编写于 作者: G Guide哥 提交者: GitHub

Merge pull request #36 from ChoKhoOu/enhancement-1

optimized SingletonFactory
......@@ -3,6 +3,7 @@ package github.javaguide.factory;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* 获取单例对象的工厂类
......@@ -11,28 +12,26 @@ import java.util.Map;
* @createTime 2020年06月03日 15:04:00
*/
public final class SingletonFactory {
private static final Map<String, Object> OBJECT_MAP = new HashMap<>();
private static final Map<String, Object> OBJECT_MAP = new ConcurrentHashMap<>();
private SingletonFactory() {
}
public static <T> T getInstance(Class<T> c) {
String key = c.toString();
Object instance = OBJECT_MAP.get(key);
if (instance != null) {
return c.cast(instance);
if (c == null) {
throw new IllegalArgumentException();
}
synchronized (SingletonFactory.class) {
instance = OBJECT_MAP.get(key);
if (instance == null) {
String key = c.toString();
if (OBJECT_MAP.containsKey(key)) {
return c.cast(OBJECT_MAP.get(key));
} else {
return c.cast(OBJECT_MAP.computeIfAbsent(key, k -> {
try {
instance = c.getDeclaredConstructor().newInstance();
OBJECT_MAP.put(key, instance);
} catch (IllegalAccessException | InstantiationException | NoSuchMethodException | InvocationTargetException e) {
return c.getDeclaredConstructor().newInstance();
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException 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.
先完成此消息的编辑!
想要评论请 注册