kotlin实现单例模式

2022-04-19  本文已影响0人  Bfmall

1.懒汉式实现单例模式

class Singleton private constructor() {

    companion object{
        private var instance:Singleton ?= null
            get() {
                if (field==null){
                    field = Singleton()
                }
                return field
            }
        fun get(): Singleton {
            return instance!!
        }
    }
}

2.线程安全懒汉式实现单例模式

/**
 * 添加了 @Synchronized注解
 */
class Singleton private constructor() {

    companion object{
        private var instance:Singleton ?= null
            get() {
                if (field==null){
                    field = Singleton()
                }
                return field
            }
        @Synchronized
        fun get(): Singleton {
            return instance!!
        }
    }

}

3.双重校验懒汉式实现单例模式

class Singleton private constructor() {

    companion object{
        val instance : Singleton  by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED){
            Singleton()
        }
    }
}

4.静态内部类方式实现单例模式

class Singleton private constructor(){

    companion object{
        val instance = Holder.instance
    }

    private object Holder{
       val instance = Singleton()
    }
}
上一篇下一篇

猜你喜欢

热点阅读