Eager
Initialized when program loads
Easy implementation
Instance created even if unused
Increased application load time
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
Lazy
Initialized on first access
Avoids unnecessary instantiation
Careful in multi-threaded apps
Increased operation wait time
May result in delayed failures
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) instance = new Singleton();
return instance;
}
}