Last active
November 7, 2015 11:14
-
-
Save StanKocken/39d604bcf8c814a48859 to your computer and use it in GitHub Desktop.
A singleton pattern, to make the Mock of it easily
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class MyManager { | |
| private MyManager() {} | |
| public static MyManager getInstance() { | |
| return Singleton.getInstance(MyManager.class); | |
| } | |
| public void myMethod() { | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class Singleton { | |
| private static final Map<Class, Object> SINGLETONS = new HashMap<>(); | |
| private Singleton() { } | |
| public static synchronized <T> T getInstance(Class<T> clazz) { | |
| T instance = (T) SINGLETONS.get(clazz); | |
| if (instance == null) { | |
| try { | |
| instance = createInstance(clazz); | |
| setInstance(clazz, instance); | |
| } catch (Exception e) { | |
| VLog.e(e); | |
| } | |
| } | |
| return instance; | |
| } | |
| public static <T> void setInstance(Class<T> clazz, T instance) { | |
| SINGLETONS.put(clazz, instance); | |
| } | |
| public static void clear() { | |
| SINGLETONS.clear(); | |
| } | |
| @NonNull | |
| private static <T> T createInstance(Class<T> clazz) | |
| throws IllegalAccessException, NoSuchMethodException, | |
| InstantiationException, InvocationTargetException { | |
| Constructor<T> constructor = clazz.getDeclaredConstructor(); | |
| constructor.setAccessible(true); | |
| return constructor.newInstance(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment