Singleton in kotlin — object
Singleton is a creational design pattern that lets you ensure that a class has only one instance, while providing a global access point to this instance.
That means it will ensure at any time only one instance of that class is created.
We usually create singleton in java like below
public class Singleton {
private static Singleton instance = null;
public Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
Oops.. what will happen if two threads access the getInstance method same time..?
Yes.It will create two instance.So we need to make it thread safe.
public class Singleton {
private static Singleton instance = null;
public Singleton getInstance() {
if (instance == null) {
synchronized (instance){
instance = new Singleton();
}
}
return instance;
}
}
now,if two thread access method at same time also it will create only one instance.
These much code we need to write for creating singleton…
Now we will see how the above code will looks like in kotlin
object Singleton {
}
that's it.
This will create a thread safe singleton class in kotlin.
Happy Reading… Happy Coding….