Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DEARaison/6d5787f1473c3bf454bd051d038ff1d1 to your computer and use it in GitHub Desktop.
Save DEARaison/6d5787f1473c3bf454bd051d038ff1d1 to your computer and use it in GitHub Desktop.
A Better Singleton template for Intellij IDEA/ Android Studio. To add go to Settings > Editor > File and Code Templates > Hit Create Template and add this one
#if (${PACKAGE_NAME} != "")package ${PACKAGE_NAME};#end
#if (${IMPORT_BLOCK} != "")${IMPORT_BLOCK}
#end
#parse("File Header.java")
#if (${VISIBILITY} == "PUBLIC")public #end class ${NAME} #if (${SUPERCLASS} != "")extends ${SUPERCLASS} #end #if (${INTERFACES} != "")implements ${INTERFACES} #end {
private static volatile ${NAME} sInstance = null;
private ${NAME}() {
if (sInstance != null) {
throw new AssertionError(
"Another instance of "
+ ${NAME}.class.getName()
+ " class already exists, Can't create a new instance.");
}
}
#if (${VISIBILITY} == "PUBLIC")public #end static ${NAME} getInstance() {
if (sInstance == null) {
synchronized (${NAME}.class) {
if (sInstance == null) {
sInstance = new ${NAME}();
}
}
}
return sInstance;
}
}
#if (${PACKAGE_NAME} != "")package ${PACKAGE_NAME}#end
class ${NAME} private constructor() {
companion object {
@Volatile
private var INSTANCE: ${NAME}? = null
private val LOCK = Any()
operator fun invoke(): ${NAME} {
return INSTANCE
?: synchronized(LOCK) {
INSTANCE
?: ${NAME}()
.also { INSTANCE = it }
}
}
}
}
#if (${PACKAGE_NAME} != "")package ${PACKAGE_NAME};#end
#if (${IMPORT_BLOCK} != "")${IMPORT_BLOCK}
#end
#parse("File Header.java")
#if (${VISIBILITY} == "PUBLIC")public #end class ${NAME} #if (${SUPERCLASS} != "")extends ${SUPERCLASS} #end #if (${INTERFACES} != "")implements ${INTERFACES} #end {
private static final ${NAME} ourInstance = new ${NAME}();
#if (${VISIBILITY} == "PUBLIC")public #end static ${NAME} getInstance() {
return ourInstance;
}
private ${NAME}() {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment