kotlin 单例

1.使用伴生对象(companion object):

class Singleton private constructor() {

companion object {

private val instance: Singleton by lazy { Singleton() }

fun getInstance(): Singleton {

return instance

}

}

// 其他类成员

}

获取实例

val instance = Singleton.getInstance()

这种方式提供了更多的灵活性,可以在伴生对象中定义一些其他的属性和方法

2.使用 object 关键字:

object Singleton {

// 单例的属性和方法

}

获取实例

val instance = Singleton

这种方式简单明了,object 关键字会自动创建单例。可以直接通过 Singleton 访问单例的属性和方法。

3.使用 lazy 委托:

class Singleton private constructor() {

companion object {

val instance: Singleton by lazy { Singleton() }

}

// 其他类成员

}

获取实例

val instance = Singleton.instance

这种方式利用 lazy 委托,确保只有在首次访问 instance 属性时才会初始化单例。

复制代码
4.使用 enum枚举类

enum class Singleton {

INSTANCE;

// 单例的属性和方法

}

获取实例

val instance = Singleton.INSTANCE

枚举类在 Kotlin 中可以用来创建单例,INSTANCE 就是这个单例的实例。

5.双重检查锁定

class Singleton private constructor() {

companion object {

@Volatile

private var instance: Singleton? = null

fun getInstance(): Singleton {

return instance ?: synchronized(this) {

instance ?: Singleton().also { instance = it }

}

}

}

// 其他类成员

}

获取实例

val instance = Singleton.getInstance()

这种方式在多线程环境下保证了懒加载的线程安全性,避免了每次获取实例都进行同步。

6.使用 Holder 模式:

class Singleton private constructor() {

private object Holder {

val INSTANCE = Singleton()

}

companion object {

fun getInstance(): Singleton {

return Holder.INSTANCE

}

}

// 其他类成员

}

获取实例

val instance = Singleton.getInstance()

这种方式通过 Kotlin 的对象声明在 Holder 类中创建单例,确保了懒加载和线程安全性。

复制代码
相关推荐
alexhilton2 天前
端侧RAG实战指南
android·kotlin·android jetpack
Kapaseker2 天前
2026年,我们还该不该学编程?
android·kotlin
Kapaseker3 天前
一杯美式搞懂 Any、Unit、Nothing
android·kotlin
Kapaseker4 天前
一杯美式搞定 Kotlin 空安全
android·kotlin
FunnySaltyFish5 天前
什么?Compose 把 GapBuffer 换成了 LinkBuffer?
算法·kotlin·android jetpack
Kapaseker5 天前
Compose 进阶—巧用 GraphicsLayer
android·kotlin
Kapaseker6 天前
实战 Compose 中的 IntrinsicSize
android·kotlin
A0微声z8 天前
Kotlin Multiplatform (KMP) 中使用 Protobuf
kotlin
alexhilton9 天前
使用FunctionGemma进行设备端函数调用
android·kotlin·android jetpack
lhDream9 天前
Kotlin 开发者必看!JetBrains 开源 LLM 框架 Koog 快速上手指南(含示例)
kotlin