Last active
December 8, 2022 07:05
-
-
Save Bloody-Badboy/f46c6b73b85583f99e21733c60605f72 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
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
#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; | |
} | |
} |
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
#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 } | |
} | |
} | |
} | |
} |
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
#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