Last active
October 7, 2020 06:48
-
-
Save kittinunf/b27eacdbe4638f34e1e2e317ebbb6e37 to your computer and use it in GitHub Desktop.
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
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