Kotlin 单例模式详解

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

Object

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

1
2
object JsonObjectMapper {
}

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

1
2
3
4
5
// Kotlin 调用
JsonObjectMapper

// Java调用
JsonObjectMapper.INSTANCE

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

image.png

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

Companion Object

懒汉式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class SingletonDemo private constructor() {
companion object {
private var instance: SingletonDemo? = null
get() {
if (field == null) {
field = SingletonDemo()
}
return field
}
fun get(): SingletonDemo{
return instance!!
}
}
}

线程安全的懒汉式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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)

1
2
3
4
5
6
class SingletonDemo private constructor() {
companion object {
val instance: SingletonDemo by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
SingletonDemo() }
}
}

静态内部类式

1
2
3
4
5
6
7
8
class SingletonDemo private constructor() {
companion object {
val instance = SingletonHolder.holder
}
private object SingletonHolder {
val holder = SingletonDemo()
}
}

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×