不带参数
-
public class Singleton private constructor() {
init { println("This ($this) is a singleton") }
private object Holder { private val INSTANCE = Singleton() }
companion object {
val instance: Singleton by lazy { Holder.INSTANCE }
}
var b:String? = null
}
-
public class Singleton private constructor() {
init { println("This ($this) is a singleton") }
companion object {
private 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!!
}
}
}