专业的编程技术博客社区

网站首页 > 博客文章 正文

Kotlin单例模式你不知道的秘密花园

baijin 2024-09-06 14:52:58 博客文章 5 ℃ 0 评论

1.使用object关键字(饿汉式)

这种方式创建的对象在第一次访问时初始化,并且是线程安全的。

object Singleton {
  fun process() {
  }
}

// 使用方式
Singleton.process()

2. 使用synchronized实现线程安全的单例(懒汉式)

可以在Kotlin中使用synchronized关键字来确保线程安全。

1)实现方式一

class Singleton private constructor() {

  fun process() {
  }

  companion object {
    @Volatile
    private var instance: Singleton? = null

    fun getInstance(): Singleton {
    if(null == instance){
      synchronized(this) {
        if (null == instance) {
          instance = Singleton()
        }
      }
    }
    return instance!!
  }
}
}

// 使用方式
Singleton.getInstance().process()

2)实现方式二

class Singleton private constructor() {
  fun process() {
  }
  companion object {
    private var instance: Singleton? = null
      get() {
        if (field == null) {
        	field = Singleton()
        }
        return field
        }
      @Synchronized
      fun get(): Singleton{
      	return instance!!
      }
  }
}
// 使用方式
Singleton.get().process()

3. 使用lazy代理

如果你有一个需要参数的类,或者想要延迟加载类实例,或者你想更精细地控制初始化过程,则可以使用lazy代理。此方式是线程安全的。

class Singleton private constructor() {

fun process() {
}

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

// 使用方式
Singleton.instance.process()

4.静态内部类式

避免类加载的时候初始化单例。

class Singleton private constructor() {
  fun process() {
  }
  companion object {
  	val instance = SingletonHolder.holder
  }
  private object SingletonHolder {
 		val holder= Singleton()
  }
}
// 使用方式
Singleton.instance.process()




若作品对您有帮助,请关注、分享、点赞、收藏、在看、喜欢。您的支持是我们为您提供帮助的最大动力。

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表