单例包装类
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
}
}
}
}
使用如下
class Manager private constructor(context: Context) {
init {
// Init using context argument
}
companion object : SingletonHolder<Manager, Context>(::Manager)
}
Manager.getInstance(context).doStuff()
无参构造函数的单例模式
interface GitHubService {
companion object {
val instance: GitHubService by lazy {
val retrofit = Retrofit.Builder()
.baseUrl("https://api.github.com/")
.build()
retrofit.create(GitHubService::class.java)
}
}
}
网友评论