23
loading...
This website collects cookies to deliver better user experience
public class Singleton {
private static Singleton instance;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
Singleton
class only has one instance, It's constructor is marked as private. Singleton
has an API called getInstance()
. getInstance
function at the same time.public class Singleton {
private volatile static Singleton instance;
private Singleton() {
}
public static synchronised Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
getInstance()
we are forcing every thread to wait it's turn before they enter the function. So only one thread can access the getInstance()
function.Object
keyword from Kotlin. Kotlin has the Singleton pattern built into the language with the Object
keyword.object Singleton {
}
23