Singleton 在 Kotlin 中

huangapple go评论63阅读模式
英文:

Singleton in Kotlin

问题

I want to implement "singleton" pattern in Kotlin. I wrote something like this.

class MySingleton {
    companion object {
        val instance = MySingleton
    }
}

But now users can create instances.

val mySingleton = MySingleton()

I want allow only this way.

val instance = MySingleton.instance

How can I ban using a constructor of my class?

英文:

I want to implement "singleton" pattern in Kotlin. I wrote something like this.

class MySingleton {
    companion object {
        val instance = MySingleton
    }
}

But now users can create instances.

val mySingleton = MySingleton()

I want allow only this way.

val instance = MySingleton.instance

How can I ban using a constructor of my class?

答案1

得分: 3

如果您使用对象而不是类,您可能会有更好的运气。

即。

object MySingleton {
    val thingA = 0
}
英文:

if you use an object instead of a class you may have better luck

ie.

object MySingleton {
    val thingA = 0
}

huangapple
  • 本文由 发表于 2020年1月7日 01:54:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/59616732.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定