單例模式(singleton):是JAVA中最簡單的一種設計模式,屬于創建型模式,所謂單例,就是整個程式有且僅有一個實體,
特點:
構造方法私有化
在本類中實體化一個物件作為本類的屬性
對外提供一個訪問本類物件的方法
餓漢式:類加載時就加載物件
應用場景:小物件,頻繁用,高并發
特點:執行緒安全,比較常用,但容易產生垃圾,影響性能,因為一開始就初始化,
1 class Singleton{ 2 //構造方法私有化 3 private Singleton() { 4 System.out.println("構造方法"); 5 } 6 //物件在類加載時初始化 7 private static final Singleton instance = new Singleton(); 8 //提供對外的訪問方法 9 public static Singleton getInstance() {10 return instance;11 }12 }
懶漢式:物件何時需要何時創建,執行緒不安全
應用場景:單執行緒,大物件
特點:執行緒不安全,延遲初始化,
1 class Singleton{ 2 private Singleton() { 3 System.out.println("構造方法"); 4 } 5 private static Singleton instance; 6 public static Singleton getInstance() { 7 if (instance == null) { 8 instance = new Singleton(); 9 }10 return instance;11 }12 }
同步鎖機制
應用場景:多執行緒,大物件,稀少用,
特點:通過加鎖保證了執行緒安全,性能會下降,
1 class Singleton{ 2 private Singleton() { 3 System.out.println("構造方法"); 4 } 5 private static Singleton instance; 6 //同步方法,執行緒安全,但性能會下降 7 public static synchronized Singleton getInstance() { 8 if (instance == null) { 9 instance = new Singleton();10 }11 return instance;12 }13 }
雙重驗證機制
應用場景:大物件,稀少用,并發量不能太大
特點:執行緒安全,延遲初始化,
1 class Singleton{ 2 private Singleton() { 3 System.out.println("構造方法"); 4 } 5 private static volatile Singleton instance; 6 //同步方法,雙重驗證,減少阻塞次數,提高性能 7 public static Singleton getInstance() { 8 if (instance == null) { 9 synchronized (Singleton.class) {10 if (instance == null) {11 instance = new Singleton();12 }13 }14 }15 return instance;16 }17 }
靜態內部類
參考場景:大物件,頻繁用,高并發
特點:延時物件創建,減少資源占用,提高系統性能
1 class Singleton{ 2 private Singleton() { 3 System.out.println("構造方法"); 4 } 5 static class Inner{ 6 private static final Singleton instance = new Singleton(); 7 } 8 public static Singleton getInstance() { 9 return Inner.instance;10 }11 }
列舉
1 enum Singleton{2 //類加載時創建3 INSTANCE;4 }
由于單例模式是創建型模式,每次呼叫都會新建一個實體,那么一個重要的問題就是反序列化,當實體被寫入到檔案到反序列化成實體時,我們需要重寫readResolve方法,以讓實體唯一,
1 private Object readResolve() throws ObjectStreamException{2 return singleton;3 }
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/42104.html
標籤:設計模式
上一篇:設計模式-結構型-組合模式
