HomeAndroidCreate Singleton Class in Kotlin?

Create Singleton Class in Kotlin?


In Kotlin, you should use the object declaration to implement singleton. Nevertheless, in the event you do not conscious of this object key phrase, you in all probability 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 traditional class
  • @Unstable and synchronized() 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 in addition a singleton occasion the place you may entry the singleton object instantly out of your code.

Constructor Argument Singleton

The limitation of this object declaration is you may’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 above.

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).

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments