Singleton is a world object that may be accessed from in every single place in your software. This text exhibits alternative ways of making it in Kotlin.
This text was initially printed at vtsen.hashnode.dev on Might 21, 2022.
In Kotlin, you should utilize the object declaration to implement singleton. Nevertheless, for those who do not conscious of this object key phrase, you most likely will do one thing like this.
Standard Singleton
class Singleton non-public constructor() {
companion object {
@Unstable
non-public lateinit var occasion: Singleton
enjoyable getInstance(): Singleton {
synchronized(this) {
if (!::occasion.isInitialized) {
occasion = Singleton()
}
return occasion
}
}
}
enjoyable present() {
println("That is Singleton class!")
}
}
enjoyable run() {
Singleton.getInstance().present()
}
non-public constructor()
is used in order that this cannot be created as normal class@Unstable
andsynchronized()
are used to verify this Singleton creation is thread-safe.
Object Declaration Singleton
This may be simplified to
object Singleton {
enjoyable present() {
println("That is Singleton class!")
}
}
enjoyable run() {
Singleton.present()
}
Singleton
is a category and likewise a singleton occasion the place you’ll be able to entry the singleton object immediately out of your code.
Constructor Argument Singleton
The limitation of this object declaration is you’ll be able to’t cross a constructor parameter to it to create the singleton object. If you wish to try this, you continue to want to make use of again the primary standard technique.
class Singleton non-public constructor(non-public val title: String) {
companion object {
@Unstable
non-public lateinit var occasion: Singleton
enjoyable getInstance(title: String): Singleton {
synchronized(this) {
if (!::occasion.isInitialized) {
occasion = Singleton(title)
}
return occasion
}
}
}
enjoyable present() {
println("That is Singleton $title class!")
}
}
enjoyable run() {
Singleton.getInstance("liang moi").present()
}
Conclusion
I personally use singleton for easy utility class (use object declaration) and database (use conference singleton technique – as a result of it’s required to cross in argument).