Kotlin實現單例模式

Rxfish發表於2017-12-06
  • 方式一(不含參)

    class Single private constructor() {
    
        init {
    //初始化
        }
    
        private object Holder {
            val INSTANCE = Single()
        }
    
        companion object {
            val instance: Single by lazy { Holder.INSTANCE }
        }
    }複製程式碼

  • 方式二(帶引數)

    class Singleton private constructor(str: String) {
        init {
            println("Init")
        }
    
        companion object {
            @Volatile
            var instance: Singleton? = null
    
            fun getInstance(a: String) {
                if (instance == null) {
                    synchronized(Singleton::class)
                    {
                        if (instance == null) {
                            instance = Singleton(a)
                        }
                    }
    
                    return instance!!
                }
            }
        }
    }複製程式碼


測試實現
      

fun main(args: Array<String>) {
    Single.instance

    Singleton.getInstance("a")
}複製程式碼


相關文章