-
1,提前初始化
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {
}public static Singleton getInstance() {
return instance;
}
}
-
2.雙重檢查鎖定 + volatile绊谭。
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;
}
}
-
3.延遲初始化占位類模式藐吮。
public class Singleton {
private static class InstanceHolder {
public static Singleton instance = new Singleton();
}private Singleton() {
}public static Singleton getInstance() {
return InstanceHolder.instance;
}
}