Sunday 5 April 2020

Singleton - Java vs Kotlin

Singleton is a widely used design pattern in our programming, because the single instance or object reference has been used to accessing their properties and that instance remains through out the  application session.

Now we can see how it will be implemented in Java and Kotlin.

Singleton Using Java:

public final class Singleton {
    private static final Singleton INSTANCE = new Singleton();
    public String property1;

    private Singleton() {
    }

    public static Singleton getInstance() {
        return INSTANCE;
    }

    public String getInfo() {
        return "SingleInfo";
    }
}

Points to be remembered on creating the Singleton class using Java.
  1. Class need to be final, in order to avoid this class to be inheritance by other.
  2. Constructors are need to be private
  3. private, static and final instance have to instantiated.
Accessing the properties and methods will be as follows.

String property1 = Singleton.getInstance().property1;
String info = Singleton.getInstance().getInfo();

Singleton in Kotlin: Here it is very crazy in kotlin, the below things does the job.

object Singleton {
    var property1: String? = null
    val info: String
        get() = "SingleInfo"
}


val property = Singleton.property1
val info = Singleton.info

Happy Coding :-)

No comments: