標籤:
---單例設計模式之餓漢式---
建立SingleInstance類
1 /** 2 * 單例設計模式之餓漢式 3 */ 4 public class SingleInstance { 5 /** 6 * 私人化構造方法 7 */ 8 private SingleInstance() {} 9 /**10 * 成員變數11 */12 private static SingleInstance instance = new SingleInstance() ;13 /**14 * 提供一個靜態成員方法,返回該對象15 */16 public static SingleInstance getInstance() {17 return instance ;18 }19 }
建立測試類別SingleInstanceDemo
1 /** 2 * 單例設計模式的思想: 保證該類在記憶體中只有一個執行個體(對象) 3 * 優點節省記憶體,提高記憶體利用率 4 */ 5 public class SingleInstanceDemo { 6 7 public static void main(String[] args) { 8 9 // 調用方法擷取對象10 SingleInstance instance1 = SingleInstance.getInstance() ;11 SingleInstance instance2 = SingleInstance.getInstance() ;12 13 // 輸出14 System.out.println(instance1 == instance2);15 }16 }
-------------------------------------------------------------------------------------------------------------
---單例設計模式之懶漢式---
建立SingleInstance2類
1 /** 2 * 單例設計模式之懶漢式 3 * 4 * 面試中寫那種單例設計模式呢? 5 * 面試中寫懶漢式: 因為懶漢式體現了兩種思想, 第一種線程問題 , 第二種 消極式載入 6 * 7 * 開發中寫餓漢式 8 */ 9 public class SingleInstance2 {10 /**11 * 私人化構造方法12 */13 private SingleInstance2() {}14 /**15 * 提供一個成員變數16 */17 private static SingleInstance2 instance = null ;18 /**19 * 提供一個靜態成員方法20 */21 public static synchronized SingleInstance2 getInstance() {22 23 if(instance == null){24 instance = new SingleInstance2() ;25 }26 return instance ;27 }28 }
建立測試類別SingleInstanceDemo2
1 public class SingleInstance2Demo { 2 3 public static void main(String[] args) { 4 5 // 擷取對象 6 SingleInstance2 instance1 = SingleInstance2.getInstance() ; 7 SingleInstance2 instance2 = SingleInstance2.getInstance() ; 8 9 // 比較10 System.out.println(instance1 == instance2);11 12 }13 14 }
單例設計模式 (代碼實現)