Kotlin 单例模式详解

2019-07-08

单例模式很熟悉了,在Java中有各种创建姿势,算是比较麻烦的,这里就不再赘述了。

Object

那么如何在kotlin中实现单例模式呢?请看代码

object JsonObjectMapper {
}

仅需简单的把class关键字替换为object就完成了!

// Kotlin 调用
JsonObjectMapper

// Java调用
JsonObjectMapper.INSTANCE

究竟Kotlin封装了什么细节?让我们一探究竟吧: 通过Tools > Kotlin > Show Kotlin Bytecode 显示字节码,看看翻译后的Java代码 image.png

image.png

翻译成Java后,发现就是一个最简单的饿汉式单例而已。

Companion Object

懒汉式

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!!
        }
    }
}

双重校验锁式(Double Check)

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