kotlin单例模式
2021-06-07 本文已影响0人
Method
饿汉式
Kotlin中类没有静态方法,kotlin可以把类声明为一个对象,该对象与其他语言的静态成员是类似
object Single {
fun logMsg(){
println("this is a msg")
}
}
懒汉式
class Single1 private constructor(){
companion object{
private var instance:Single1? = null
fun getInstance():Single1{
if(instance == null){
instance = Single1()
}
return instance!!
}
}
}
双重校验
// 双重校验
class Single2{
companion object{
val instance by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { Single2() }
}
}
静态内部类
// 静态内部类
class Single3{
companion object{
fun getInstance():Single3{
return Inner.instance
}
}
private object Inner{
val instance = Single3()
}
}