Singleton design pattern in Java
public class Main {
public static void main(String[] args) {
Singleton x = Singleton.getInstance();
Singleton y = Singleton.getInstance();
System.out.println("The same objects: " + (x == y)); // true
}
}
class Singleton {
private Singleton(){};
private static Singleton INSTANCE = new Singleton();
public static Singleton getInstance() {
return INSTANCE;
}
}
- Interviewer: Go with Lazy initialization.
class Singleton {
private Singleton(){};
private static Singleton INSTANCE;
public static Singleton getInstance() {
if (INSTANCE == null)
INSTANCE = new Singleton();
return INSTANCE;
}
}
- Interviewer: Support multi-threading.
class Singleton {
private Singleton(){};
private static Singleton INSTANCE;
public static Singleton getInstance() {
if (INSTANCE == null) {
synchronized (Singleton.class) {
if (INSTANCE == null)
INSTANCE = new Singleton();
}
}
return INSTANCE;
}
}