饿汉单例
object SingletonDemo
懒汉单例
class SingletonDemo private constructor() {
companion object {
private var instance: SingletonDemo? = null
//这里使用的是自定义访问器
get() {
if (field == null) {
field = SingletonDemo()
}
return field
}
fun get(): SingletonDemo{
return instance!!
}
}
}
线程安全的懒汉单例
class SingletonDemo private constructor() {
companion object {
private var instance: SingletonDemo? = null
get() {
if (field == null) {
field = SingletonDemo()
}
return field
}
//使用同步锁注解
@Synchronized
fun get(): SingletonDemo{
return instance!!
}
}
}
双重校验锁
class SingletonDemo private constructor() {
companion object {
val instance: SingletonDemo by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
SingletonDemo() }
}
}
静态内部类模式
class SingletonDemo private constructor() {
companion object {
val instance = SingletonHolder.holder
}
private object SingletonHolder {
val holder= SingletonDemo()
}
}