Created
March 31, 2019 02:59
-
-
Save f2face/90320f849fc7ca1002114e5698b0dc94 to your computer and use it in GitHub Desktop.
Android/Java Singleton class boilerplate.
This file contains 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
/* | |
* A Singleton class, based on an article on Medium, "How to make the perfect Singleton?" | |
* Link: https://medium.com/@kevalpatel2106/how-to-make-the-perfect-singleton-de6b951dfdb0 | |
*/ | |
package com.myapp.singleton; // Your package name | |
public class MySingleton { | |
private static volatile MySingleton instance; | |
private MySingleton() { | |
if (instance != null) { | |
throw new RuntimeException("Use getInstance() method to get the single instance of this class."); | |
} | |
} | |
public static MySingleton getInstance() { | |
if (instance == null) { | |
synchronized (MySingleton.class) { | |
if (instance == null) instance = new MySingleton(); | |
} | |
} | |
return instance; | |
} | |
//////////////////////////////////////////////// | |
// Put your code here | |
//////////////////////////////////////////////// | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment