45 lines
1.0 KiB
Kotlin
45 lines
1.0 KiB
Kotlin
package com.dahe.mylibrary.base
|
|
|
|
/**
|
|
* @ClassName SingletonHolder
|
|
* @Author john
|
|
* @Date 2024/2/5 15:35
|
|
* @Description TODO
|
|
*/
|
|
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 =
|
|
instance ?: synchronized(this) {
|
|
instance ?: creator!!(arg).apply {
|
|
instance = this
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
open class SingletonNoPHolder<out T>(creator: () -> T) {
|
|
|
|
private var creator: (() -> T)? = creator
|
|
|
|
@Volatile
|
|
private var instance: T? = null
|
|
|
|
//对上述方法的一种更简洁的写法
|
|
fun getInstance(): T =
|
|
instance ?: synchronized(this) {
|
|
instance ?: creator!!().apply {
|
|
instance = this
|
|
}
|
|
}
|
|
}
|
|
|
|
//使用
|
|
//class SkinManager private constructor(context: Context) {
|
|
// companion object : SingletonHolder<SkinManager, Context>(::SkinManager)
|
|
//} |