一種對象創建模式,確保系統中的一個類只產生一個實例
2.減輕GC壓力,縮短GC停頓時間
參與者:
單例類,提供單例的工廠
使用者,獲取並使用單例
在多線程中時耗遠高於第一種,但可以延遲加載
兩大好處:
1.對於頻繁使用的對象,可以減少創建的系統開銷2.減輕GC壓力,縮短GC停頓時間
參與者:
單例類,提供單例的工廠
使用者,獲取並使用單例
第一種:
首先,單例類必須要有一個private訪問級別的構造函數,其次instance變量和getInstance()必須是static的無法對instance延遲加載,由於instance是static,因此JVM加載單例類時就創建
public class Singleton{
private Singleton(){}
private static Singleton instance = new Singleton();
public static Singleton getInstance(){
return instance;
}
}
第二種:
在getInstance()中創建instance,需要對getInstance()加同步關鍵字synchronized在多線程中時耗遠高於第一種,但可以延遲加載
public class Singleton{
private Singleton(){}
private static Singleton instance = null;
public static synchronized Singleton getInstance(){
if(instance == null)
instance = new Singleton();
return instance;
}
第三種:
使用內部類維護單例,既可以延遲加載又不必使用同步關鍵字
public class Singleton{
private Singleton(){}
private static class SingletonHolder{ //加了static外圍類才能訪問到instance
private static Singleton instance = new Singleton(); //這個static是因爲只能存在一個instance
}
public static Singleton getInstance(){
return SingletonHolder.instance;
}
}