Kotlin单例模式

不带参数

1.

public class Singleton private constructor() { init { println("This ($this) is a singleton") } private object Holder { val INSTANCE = Singleton() } companion object { val instance: Singleton by lazy { Holder.INSTANCE } } var b:String? = null
}

2.

public class Singleton private constructor() { init { println("This ($this) is a singleton") } companion object { val instance: = Singleton() } var b:String? = null
}

带参数

class Singleton private constructor(str: String) {
    var string: String = str;

    init {
        println("str is $str")
        println("string is $string")
    }

    companion object {
        @Volatile
        var instance: Singleton? = null

        fun getInstance(c: String): Singleton {
            if (instance == null) {
                synchronized(Singleton::class) {
                    if (instance == null) {
                        instance = Singleton(c)
                    }
                }
            }
            return instance!!
        }
    }
}

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