Skip to content

Instantly share code, notes, and snippets.

@kittinunf
Last active October 7, 2020 06:48
Show Gist options
  • Save kittinunf/b27eacdbe4638f34e1e2e317ebbb6e37 to your computer and use it in GitHub Desktop.
Save kittinunf/b27eacdbe4638f34e1e2e317ebbb6e37 to your computer and use it in GitHub Desktop.
open class Holder<out T: Any, in A>(creator: (A) -> T) {
private var creator: ((A) -> T)? = creator
@Volatile private var instance: T? = null
fun instance(arg: A): T {
val ins = instance
if (ins != null) {
return ins
}
return synchronized(this) {
val ins2 = instance
if (ins2 != null) {
ins2
} else {
val created = creator!!(arg)
instance = created
creator = null
created
}
}
}
}
//usage
class FooManager private constructor(context: Context) {
init {
// Init using context argument
}
companion object : Holder<Manager, Context>(::FooManager)
}
FooManager.instance(context)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment