kotlin Singleton Pattern

Singleton pattern is a design solution where an application wants to have one and only one instance of any class, in all possible scenarios without any exceptional condition.

The singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

Kotlin doesn’t have static member for class, it means that you can’t create static method and static variable in Kotlin class. So, how can we create singleton class in Kotlin?

Fortunately, Kotlin object can handle this. Specific to class, companion object keyword is used for its member to be accessible.


class MyClass { 
  companion object Factory {
    val info = "This is factory"    
    fun getMoreInfo():String { return "This is factory fun" }
  } 
}
MyClass.getMoreInfo()			

Every properties and method inside companion object can be called directly by using class name (sounds like static eh.). And now, we can create a singleton class based on initialization-on-demand holder pattern.

use object instead


public class Singleton private constructor() {
    init { println("This ($this) is a singleton") }    

    private object Holder { val INSTANCE = Singleton() }

    companion object {
        val instance: Singleton by lazy { Holder.INSTANCE }
    }
    var b:String? = null
}			

  • private constructor is used to ensure this class can’t be initialized anywhere except inside of this class.
  • init will be called when this class is initialized the first time i.e. when Singleton.instance called the very first.
  • Holder object & lazy instance is used to ensure only one instance of Singleton is created.
Output of the Singleton pattern in kotlin

var first = Singleton.instance  // This (Singleton@7daf6ecc) is a
                                // singleton
first.b = "hello singleton"

var second = Singleton.instance
println(first.b)        // hello singleton			
println(second.b)        // hello singleton			

 
Join My Facebook Group
Join Group
 
aaaaaaaaaaaaa
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Recent Addition

new tutorial Selenium Online Training : Our next online training course for Selenium with Java starts from 17th December 2018.

You can attend first 3 classes for free, the total course fee is INR 10,000

The course time would be 8.00 PM(IST) for the first three classes

If you are interested to learn, then you can join the course by sending email to chercher.tech@gmail.com

or Register below


 
Join My Facebook Group
Join Group