饿汉模式:
public class HungrySingleton {
private HungrySingleton() {} ❶
private static HungrySingleton instance = new HungrySingleton();❷
public static HungrySingleton getInstance() {
return instance;
}
}
懒汉模式:
public class LazySingleton {
private static LazySingleton instance = null; ❶
private LazySingleton() {
}
public static LazySingleton getInstance() { ❷
if(instance == null){ ❸
instance = new LazySingleton();
}
return instance;
}
}
线程安全懒汉模式:
public class LazySingleton {
private LazySingleton() {
}
private static volatile LazySingleton instance = null; ❶
public static synchronized LazySingleton getInstance() { ❷
if(instance == null){
instance = new LazySingleton();
}
return instance;
}
}
双重检测锁:
public class LazySingleton {
private LazySingleton() {
}
private static volatile LazySingleton instance = null; ❷
public static LazySingleton getInstance(){ ❶
if(instance == null){ ❸
synchronized (LazySingleton.class) { ❺
if(instance == null) ❹
instance = new LazySingleton();❻
}
}
return instance;
}
}