-
单例模式 - 饿汉式
/** * * @Description 饿汉式-定义一个object对象表达式即可,无需手动去设置构造器私有化和提供全局访问点 */ object SingleTon1
-
单例模式-懒汉式
- 无参数
/** * @Description 懒汉式 - 无参数传入 */ class Singleton2 private constructor() { companion object { private var INSTANCE: Singleton2? = null get() { return field ?: Singleton2() } fun getInstance(): Singleton2 { return INSTANCE!! } } }
- 有参数
/** * @Description 懒汉式 - 有参数出阿努如 */ class Singleton2Params private constructor(val context: Context) { companion object { private var INSTANCE: Singleton2Params? = null fun getInstance(context: Context): Singleton2Params { return INSTANCE ?: Singleton2Params(context) } } }
- 懒汉式安全
/** * @Description 懒汉式安全,方法同步用 @Synchronized */ class Singleton3 private constructor() { companion object { private var INSTANCE: Singleton3? = null get() { return field ?: Singleton3() } @JvmStatic // @JvmStatic 在Java中可以直接调用 @Synchronized fun getInstance(): Singleton3 { return INSTANCE!! } } }
-
单例模式-双重锁DCL
- 基本
/** * @Description DCL */ class Singleton4 private constructor() { companion object { @Volatile private var INSTANCE: Singleton4? = null fun getInstance(): Singleton4 { if (INSTANCE == null) { synchronized(this) { if (INSTANCE == null) { INSTANCE = Singleton4() } } } return INSTANCE!! } } }
- by lazy 写法
/** * @Description DCL */ class Singleton4DCL private constructor() { companion object { val INSTANCE: Singleton4DCL by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { Singleton4DCL() } } }
- 和 1 一样,换一种写法
/** * @Description DCL */ class Singleton4DCLNew private constructor() { companion object { @Volatile private var INSTANCE: Singleton4DCLNew? = null fun getInstance(): Singleton4DCLNew = INSTANCE ?: synchronized(this) { INSTANCE ?: Singleton4DCLNew() //instanceTon ?: Singleton4DCLNew().also { instanceTon = it } //instanceTon ?: Singleton4DCLNew().let { it } //instanceTon ?: Singleton4DCLNew().run { this } //instanceTon ?: Singleton4DCLNew().apply { instanceTon = this } } } }
- DCL传入参数
class SingleInstance private constructor(private val mContext: Context) { companion object { @Volatile private var INSTANCE: SingleInstance? = null fun getInstance(context: Context): SingleInstance = INSTANCE ?: synchronized(this) { INSTANCE ?: SingleInstance(context) } } fun doSomeThing() { val string = mContext.resources.getString(R.string.app_name) Log.d("singleDcl", string) } }
-
单例模式-枚举
/**
* @Description 枚举单例模式
*/
enum class SingleTonEnum {
INSTANCE;
fun doSomething() {
println("do some thing")
}
}
- 单例模式-静态内部类
/**
* @Description 静态内部类式
*/
class Singleton5 private constructor() {
companion object {
val INSTANCE: Singleton5 = Inner.INSTANCE
}
private object Inner {
val INSTANCE: Singleton5 = Singleton5()
}
}
网友评论