java單例模式優缺點(懶漢模式,餓漢模式,雙重檢查加鎖模式)
阿新 • • 發佈:2019-02-19
三種單例模式實際都是有運用的。
優點:延遲載入
缺點:不加同步的懶漢式是執行緒不安全的,加了synchronized之後就變成執行緒安全的了
public class Singleton { private static Singleton singleton = null; private Singleton(){ } public static synchronized Singleton getInstance(){ if(singleton == null){ singleton = new Singleton(); } return singleton; } }
優點:執行緒安全
缺點:浪費記憶體空間
例項應用:java.lang.Runtime
public class Singleton {
private static final Singleton singleton = new Singleton();
private Singleton(){
}
public static Singleton getInstance(){
return singleton ;
}
}
特點:效能又保證執行緒安全
public class Singleton{ private static Singleton singleton; private Singleton(){ } public static Singleton getInstance(){ if(singleton == null){ synchronized(Singleton.class){ if(singleton == null){ singleton = new Singleton(); } } } return singleton; } }