A Lazy Mode of Writing in Kotlin Singleton Mode

A Lazy Mode of Writing in Kotlin Singleton Mode

class MyHelpler {
    companion object {
        private val singleHelpler by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { MyHelpler() }
        fun instance() = singleHelpler
    }

    fun sayHi() {
        println("fly")
    }
}

fun main(args: Array<String>) {
    MyHelpler.instance().sayHi()
}

Kotlin implements singleton mode with object, companion object and java static_zhangphil's blog-CSDN blog It is easy to use object to implement singleton mode in java in kotlin. Since there is no static modifier in kotlin, the static effect in Java can be realized with companion object. Kotlin uses object to implement singleton mode, companion object and java static. You can see that the Singleton defined by object is only initialized once. method - mymethod. https://blog.csdn.net/zhangphil/article/details/129242135 kotlin constructor init companion object and initialization by lazy_zhangphil's blog-CSDN blog Kotlin is easy to use object to implement the singleton pattern in java. Since there is no static modifier in kotlin, the static effect in Java can be realized with companion object. Kotlin uses object to implement singleton mode, companion object and java static. method - mymethod. lazy is used in singleton mode, and will be executed if and only when the variable is called for the first time. Classes that consume heavy resource initialization. Kotlin implements singleton mode with object, companion object and java static_zhangphil's blog-CSDN blog. https://blog.csdn.net/zhangphil/article/details/131134982

Guess you like

Origin blog.csdn.net/zhangphil/article/details/131555421