实现方式1
class KLazilyDCLSingleton private constructor() : Serializable {
fun doSomething() {
println("do some thing")
}
private fun readResolve(): Any {
return instance
}
companion object {
@JvmStatic
val instance: KLazilyDCLSingleton by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { KLazilyDCLSingleton() }
}
}
实现方式2
class KOptimizeSingleton private constructor(): Serializable {
companion object {
@JvmStatic
fun getInstance(): KOptimizeSingleton {
return SingletonHolder.mInstance
}
}
fun doSomething() {
println("do some thing")
}
private object SingletonHolder {
val mInstance: KOptimizeSingleton = KOptimizeSingleton()
}
private fun readResolve(): Any {
return SingletonHolder.mInstance
}
}
方式3:静态方法调用
class TopLevelClass {
companion object {
fun doSomeStuff() {
...
}
}
object FakeCompanion {
fun doOtherStuff() {
...
}
}
}
fun testCompanion() {
TopLevelClass.doSomeStuff()
TopLevelClass.Companion.doSomeStuff()
TopLevelClass.FakeCompanion.doOtherStuff()
}
|