|
@@ -0,0 +1,28 @@
|
|
|
|
+package singletonPattern;
|
|
|
|
+
|
|
|
|
+import java.lang.reflect.Constructor;
|
|
|
|
+import java.lang.reflect.InvocationTargetException;
|
|
|
|
+import java.util.Arrays;
|
|
|
|
+import java.util.Objects;
|
|
|
|
+import java.util.concurrent.ConcurrentHashMap;
|
|
|
|
+
|
|
|
|
+public class SingletonFactory {
|
|
|
|
+ private static ConcurrentHashMap<Class, Object>map = new ConcurrentHashMap<>();
|
|
|
|
+
|
|
|
|
+ public synchronized static <T> T getInstance(Class<T> clazz,Object ... args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
|
|
|
|
+ //判断map中是否已经有
|
|
|
|
+ if(map.containsKey(clazz)) {
|
|
|
|
+ return (T) map.get(clazz);
|
|
|
|
+ }
|
|
|
|
+ //构造函数的参数
|
|
|
|
+ Class[] classes=null;
|
|
|
|
+ if(args!=null&&args.length>0){
|
|
|
|
+ classes = Arrays.stream(args).map(Object::getClass).toArray(Class[]::new);
|
|
|
|
+ }
|
|
|
|
+ Constructor<T> constructor = clazz.getConstructor(classes);
|
|
|
|
+ T o = constructor.newInstance(args);
|
|
|
|
+ map.put(clazz,o);
|
|
|
|
+ return o;
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+}
|