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
| public 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 (Exception e) { throw new RuntimeException(e.getMessage(), e); } })); } } }
|