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

[fix]单例对象的工厂类

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