Kotlin 单例

111 阅读1分钟

双重锁实现方式

针对无参构造函数

class Test private constructor() {

    companion object {
        val instance by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { Test() }
    }
}

针对带参构造函数

class Test private constructor(context:Context) {

    companion object {
        private var instance: Test? = null

        fun getInstance(context: Context) = instance ?: synchronized(this) {
            instance ?: Test(context).also { instance = it }
        }
    }
}