class KLazilyDCLSingleton private constructor() : Serializable {//private constructor()構造器私有化
fun doSomething() {
println("do some thing")
}
private fun readResolve(): Any {//防止單例對象在反序列化時重新生成對象
return instance
}
companion object {
//通過@JvmStatic註解,使得在Java中調用instance直接是像調用靜態函數一樣,
//類似KLazilyDCLSingleton.getInstance(),如果不加註解,在Java中必須這樣調用: KLazilyDCLSingleton.Companion.getInstance().
@JvmStatic
//使用lazy屬性代理,並指定LazyThreadSafetyMode爲SYNCHRONIZED模式保證線程安全
val instance: KLazilyDCLSingleton by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { KLazilyDCLSingleton() }
}
}
//在Kotlin中調用,直接通過KLazilyDCLSingleton類名調用instance
fun main(args: Array<String>) {
KLazilyDCLSingleton.instance.doSomething()
}
//在Java中調用
public class TestMain {
public static void main(String[] args) {
//加了@JvmStatic註解後,可以直接KLazilyDCLSingleton.getInstance(),不會打破Java中調用習慣,和Java調用方式一樣。
KLazilyDCLSingleton.getInstance().doSomething();
//沒有加@JvmStatic註解,只能這樣通過Companion調用
KLazilyDCLSingleton.Companion.getInstance().doSomething();
}
}
參考文獻: