-
Notifications
You must be signed in to change notification settings - Fork 2k
/
SingletonFactory.java
36 lines (32 loc) · 1.09 KB
/
SingletonFactory.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package github.javaguide.factory;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* 获取单例对象的工厂类
*
* @author shuang.kou
* @createTime 2020年06月03日 15:04:00
*/
public final class SingletonFactory {
private static final Map<String, Object> OBJECT_MAP = new ConcurrentHashMap<>();
private SingletonFactory() {
}
public static <T> T getInstance(Class<T> c) {
if (c == null) {
throw new IllegalArgumentException();
}
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 {
return c.getDeclaredConstructor().newInstance();
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new RuntimeException(e.getMessage(), e);
}
}));
}
}
}