Singleton with argument in Kotlin

前端 未结 5 1005
醉酒成梦
醉酒成梦 2020-12-05 23:35

The Kotlin reference says that I can create a singleton using the object keyword like so:

object DataProviderManager {
  fun registerDataProvider(pr         


        
5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-05 23:55

    With most of the existing answers it's possible to access the class members without having initialized the singleton first. Here's a thread-safe sample that ensures that a single instance is created before accessing any of its members.

    class MySingleton private constructor(private val param: String) {
    
        companion object {
            @Volatile
            private var INSTANCE: MySingleton? = null
    
            @Synchronized
            fun getInstance(param: String): MySingleton = INSTANCE ?: MySingleton(param).also { INSTANCE = it }
        }
    
        fun printParam() {
            print("Param: $param")    
        }
    }
    

    Usage:

    MySingleton.getInstance("something").printParam()
    

提交回复
热议问题