Skip to content

Instantly share code, notes, and snippets.

@NaserKhoshfetrat
Created January 22, 2022 12:42
Show Gist options
  • Save NaserKhoshfetrat/83a82906860cd3f4bfbad43fe5ed4466 to your computer and use it in GitHub Desktop.
Save NaserKhoshfetrat/83a82906860cd3f4bfbad43fe5ed4466 to your computer and use it in GitHub Desktop.
open class SingletonHolder<out T, in A>(private val constructor: (A) -> T) {
@Volatile
private var instance: T? = null
fun getInstance(arg: A): T {
return when {
instance != null -> instance!!
else -> synchronized(this) {
if (instance == null) instance = constructor(arg)
instance!!
}
}
}
}
/*usage :
* class MyManager private constructor(context: Context) {
fun doSomething() {
...
}
companion object : SingletonHolder<MyManager, Context>(::MyManager)
}
*
*
* Finally:
*
* MyManager.getInstance(context).doSomething()
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment