object 饿汉


class 懒汉 private constructor() {
companion object {
private var instance: 懒汉? = null
get() {
if (field == null) {
field = 懒汉()
}
return field
}
fun getIns(): 懒汉 {
return instance!!
}
}
}

class 线程安全懒汉 private constructor() {
companion object {
private var instance: 线程安全懒汉? = null
get() {
if (field == null) {
field = 线程安全懒汉()
}
return field
}

@Synchronized
fun getIns(): 线程安全懒汉 {
return instance!!
}
}
}


class 双重校验懒汉 private constructor() {
companion object {
val instance: 双重校验懒汉 by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { 双重校验懒汉() }
}
}

class 静态内部类 private constructor() {
companion object {
val instance: 静态内部类 = Holder.holder
}

private object Holder {
val holder = 静态内部类()
}
}

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注