Skip to content

Instantly share code, notes, and snippets.

@f2face
Created March 31, 2019 02:59
Show Gist options
  • Save f2face/90320f849fc7ca1002114e5698b0dc94 to your computer and use it in GitHub Desktop.
Save f2face/90320f849fc7ca1002114e5698b0dc94 to your computer and use it in GitHub Desktop.
Android/Java Singleton class boilerplate.
/*
* 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