- Early initialization,
- Lazy initialization.
For early initialization:
- Singleton with public final field
public class Singleton {
public static final Singleton INSTANCE = new Singleton();
private Singleton() {
//do something
}
public void someMethod() {
// do something
}
}
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {
//do something
}
public static Singleton getInstance(){
return INSTANCE
}
public void someMethod() {
// do something
} }
3. Singleton with enum
public enum Singleton {
INSTANCE;
private Singleton() {
//do something
}
public void someMethod() {
// do something
} }
For lazy initialization:
However unless you absolutely need it, don't use lazy initialization.
1. Lazy initialization holder class idiom for static fields (a class will not be initialized until it is used)
public class LazySingleton {
private static class SingletonHolder {
static final LazySingleton INSTANCE = new LazySingleton();
}
private LazySingleton() {
//do something
}
public static LazySingleton getInstance(){
return SingletonHolder.INSTANCE;
}
public void someMethod() {
// do something
}}
2. Double-check idiom for lazy initialization
class LazySingleton {
private static volatile LazySingleton instance;
private LazySingleton(){
//do something
}
public static LazySingleton getInstance() {
if (instance == null) {
synchronized (LazySingleton.class) {
if (instance == null) {
INSTANCE = new LazySingleton();
}
}
}
return instance;
}
}
No comments:
Post a Comment