Kotlin单例模式

1.不带参数

//lazy实现
class Single private constructor(){
        private object Holder {
            val INSTANCE = Single()
        }
        companion object {
            val instance :Single by lazy { Holder.INSTANCE }
        }
    }

//
class Single private constructor() {
    companion object {
        val instance = Single()
    }
}

2.带参数

class Single private constructor(context: Context) {
    companion object {
        var instance: Single? = null
        fun getInstance(context: Context): Single {
            if (instance == null) {
                synchronized(Single::class) {
                    if (instance == null) {
                        instance = Single(context)
                    }
                }
            }
            return instance!!
        }
    }
}

你可能感兴趣的:(Kotlin单例模式)