【Kotlin设计模式】Kotlin中单例模式

前言

单例模式(Singleton Pattern),是确保一个类只有一个实例,并提供一个全局访问点来访问这个实例。在 Android 中,有许多系统服务和 API 使用了单例模式,比如:

Context: 通过getApplicationContext() 获取到的进程中全局唯一Context上下文对象。

SharedPreferences: 通过 getSharedPreferences()获取 ,使用单例模式来管理应用程序中的持久化数据。在进程中是全局唯一的。

还有一些常用的系统服务管理类,比如WindowManagerWifiManagerConnectivityManager等等

实现

Kotlin中实现单例的方式比较简单,它提供了关键字object声明单例模式,编译器会自动确保实例的唯一性和线程安全性。

kotlin 复制代码
object Singleton {

    private const val name = "Ho"

    fun showName() {
        println("My name is: $name")
    }
}


Singleton.showName()

正常开发中,有些功能需要在单例类中初始化,在init代码块中进行操作即可。

kotlin 复制代码
object Singleton {

    private const val name = "Ho"

    //做初始化操作
    init {
        println("Singleton class invoked.")
    }

    fun showName() {
        println("My name is: $name")
    }
}

在某些情况下,我们希望实现延时加载单例,只有在第一次使用的时候再进行创建,Kotlin中提供了by lazy来实现懒加载。

kotlin 复制代码
class LazySingleton private constructor(){

    private  val name = "Ho"
    
    companion object{
        val instance: LazySingleton by lazy { LazySingleton() }
    }

    //做初始化操作
    init {
        println("LazySingleton class invoked.")
    }

    fun showName() {
        println("My name is: $name")
    }
}

总结

Kotlin 的单例模式通过 object 关键字实现,简洁且线程安全。对于需要懒加载的情况,可以使用 by lazy 实现。

相关推荐
yeziyfx1 小时前
kotlin中 ?:的用法
android·开发语言·kotlin
刀法如飞1 小时前
开箱即用的 DDD(领域驱动设计)工程脚手架,基于 Spring Boot 4.0.1 和 Java 21
java·spring boot·mysql·spring·设计模式·intellij-idea
GISer_Jing5 小时前
AI Agent 人类参与HITL与知识检索RAG
人工智能·设计模式·aigc
Tiny_React10 小时前
Claude Code Skills 自优化架构设计
人工智能·设计模式
胖虎113 小时前
iOS中的设计模式(十)- 中介者模式(从播放器场景理解中介者模式)
设计模式·中介者模式·解耦·ios中的设计模式
Geoking.13 小时前
【设计模式】组合模式(Composite)详解
java·设计模式·组合模式
刀法孜然13 小时前
23种设计模式 3 行为型模式 之3.6 mediator 中介者模式
设计模式·中介者模式
Kapaseker14 小时前
千锤百炼写View 摸爬滚打名声就
android·kotlin
Yu_Lijing14 小时前
基于C++的《Head First设计模式》笔记——单件模式
c++·笔记·设计模式
Geoking.14 小时前
【设计模式】外观模式(Facade)详解
java·设计模式·外观模式