Skip to content

Instantly share code, notes, and snippets.

@twlkyao
Created May 5, 2019 06:43
Show Gist options
  • Save twlkyao/e276ad2b05290100184a0f162974d4a0 to your computer and use it in GitHub Desktop.
Save twlkyao/e276ad2b05290100184a0f162974d4a0 to your computer and use it in GitHub Desktop.
kotlin带参的单例
/**
* 参考https://medium.com/@BladeCoder/kotlin-singletons-with-argument-194ef06edd9e
*/
open class SingletonHolder<out T, in A>(creator: (A) -> T) {
private var creator: ((A) -> T)? = creator
@Volatile private var instance: T? = null
fun getInstance(arg: A): T {
val i = instance
if (i != null) {
return i
}
return synchronized(this) {
val i2 = instance
if (i2 != null) {
i2
} else {
val created = creator!!(arg)
instance = created
creator = null
created
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment