2.1.1 單例模式

一種對象創建模式,確保系統中的一個類只產生一個實例

兩大好處:

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;
     }
}



發佈了42 篇原創文章 · 獲贊 10 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章