其他分享
首页 > 其他分享> > kotlin中的单例模式

kotlin中的单例模式

作者:互联网

饿汉单例

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()
    }
}

标签:null,field,kotlin,object,private,instance,模式,单例,SingletonDemo
来源: https://blog.csdn.net/xiaopihair123/article/details/121913878