Java設計模式——單例模式
阿新 • • 發佈:2020-07-06
類的單例設計模式:採取一定的方法保證在整個的軟體系統中,對某個類只能存在一個物件例項,並且該類只提供一個取得其物件例項的方法靜態方法 。
①
/* * 餓漢式1:靜態變數 */ class Singleton { private Singleton() { }; private final static Singleton instance = new Singleton(); public static Singleton getInstance() { return instance; } }
②
1 /* 2* 餓漢式2:靜態程式碼塊 3 */ 4 class Singleton { 5 private Singleton() { 6 }; 7 8 private static Singleton instance; 9 static { 10 instance = new Singleton(); 11 } 12 13 public static Singleton getInstance() { 14 return instance; 15 } 16 }
③
1 /*2 * 懶漢式1:執行緒不安全 3 */ 4 class Singleton { 5 private Singleton() { 6 }; 7 8 private static Singleton instance; 9 10 public static Singleton getInstance() { 11 if(instance == null){ 12 instance = new Singleton(); 13 } 14 return instance;15 } 16 }
④
1 /* 2 * 懶漢式2:執行緒安全,併發小 3 */ 4 class Singleton { 5 private Singleton() { 6 }; 7 8 private static Singleton instance; 9 10 public static synchronized Singleton getInstance() { 11 if(instance == null){ 12 instance = new Singleton(); 13 } 14 return instance; 15 } 16 }
⑤
1 /* 2 * 雙重校驗:效率高,延遲載入,執行緒安全, 3 */ 4 class Singleton { 5 private Singleton() { 6 }; 7 8 private static volatile Singleton instance; 9 10 public static Singleton getInstance() { 11 if (instance == null) { 12 synchronized (Singleton.class) { 13 if (instance == null) { 14 instance = new Singleton(); 15 } 16 } 17 } 18 return instance; 19 } 20 }
⑥
1 /* 2 * 靜態內部類 3 * 1.類載入時,靜態內部類不載入,實現懶載入 4 * 2.執行緒呼叫靜態內部類時,JVM載入機制保證執行緒安全(類初始化,別的執行緒無法進入) 5 */ 6 class Singleton { 7 private Singleton() { 8 }; 9 10 private static class SingletonInstance { 11 private final static Singleton INSTANCE = new Singleton(); 12 } 13 14 public static Singleton getInstance() { 15 return SingletonInstance.INSTANCE; 16 } 17 }
⑦
1 /* 2 * 列舉類:藉助jdk1.5列舉來實現單例模式 3 * 避免多執行緒同步問題,能防止反序列化重新建立新的物件 4 */ 5 enum Singleton { 6 INSTANCE; 7 }
總結:
1)單例模式保證了系統記憶體中該類只存在一個物件,節省了系統資源,對於一些需要頻繁建立銷燬的物件,使用單例模式可以提高系統性能
2)當想例項化一個單例類的時候,必須要記住使用相應的獲取物件的方法,而不是使用new
3)場景:需要頻繁的進行建立和銷燬的物件、建立物件時耗時過多或耗費資源過多。如:重量級物件但又經常用到的物件、工具類物件、頻繁訪問資料庫或檔案的物件;比如資料來源、 sessionFactory等。