Java單例模式的實現方法有以下幾種:
public class Singleton {
private static Singleton instance;
private Singleton(){}
public static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
可以通過在getInstance()
方法上加鎖synchronized
來實現線程安全的懶漢式單例模式,但是會影響效率:
public class Singleton {
private static Singleton instance;
private Singleton(){}
public static synchronized Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return instance;
}
}
由于在類加載時就創建實例,因此無法實現延遲加載。
public class Singleton {
private volatile static Singleton instance;
private Singleton(){}
public static Singleton getInstance(){
if(instance == null){
synchronized (Singleton.class){
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
使用volatile
修飾instance
變量可以保證多線程環境下的可見性和有序性。
public class Singleton {
private Singleton(){}
private static class SingletonHolder{
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance(){
return SingletonHolder.INSTANCE;
}
}
靜態內部類只有在第一次使用時才會被加載,從而實現了延遲加載。
public enum Singleton {
INSTANCE;
public void doSomething(){
// do something
}
}