Junior — Middle
Can you provide examples of different ways to implement the Singleton pattern?
sobes.tech AI
Answer from AI
In Java, the Singleton pattern can be implemented in several ways:
- Lazy initialization with synchronization
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
- Lazy initialization with double-checked locking
public class Singleton {
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
- Eager initialization at class loading
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
- Using enum (recommended approach since Java 5+)
public enum Singleton {
INSTANCE;
public void someMethod() {
// ...
}
}
This method guarantees thread safety and protection against serialization.
Each approach has its pros and cons regarding thread safety, performance, and implementation simplicity.