Created
January 22, 2022 12:42
-
-
Save NaserKhoshfetrat/83a82906860cd3f4bfbad43fe5ed4466 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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