面試題(單例模式兩種寫法)
阿新 • • 發佈:2019-01-28
第一種形式:餓漢式單例
public class Singleton {
private Singleton(){}
private static Singleton instance = new Singleton();
public static Singleton getInstance(){
return instance;
}
}
第二種形式:懶漢式單例
public class Singleton { private static Singleton instance = null; private Singleton() {} public static synchronized Singleton getInstance(){ if (instance==null) instance=newSingleton(); return instance; } }
區別:
<strong>“懶漢式”是在你真正用到的時候才去建這個單例物件,執行緒安全</strong>