第0章:簡介
單例模式定義:保證一個類僅有一個實例,並提供一個訪問它的全局訪問點。
單例模式本質:控制實例數目。
參考:http://chjavach.iteye.com/blog/721076 ,研磨設計模式(書籍),大話設計模式(書籍)
模式圖:
待補充
第1章:實踐
第0節:懶漢式單例模式(非線程安全,延遲加載)
package com.mcc.core.designPattern.build.singleton; /** //全局靜態實例 /** } /** public static LazySingleton getInstance(){ |
第1節:餓漢式單例模式(線程安全,預加載)
package com.mcc.core.designPattern.build.singleton; /** * 餓漢式單例模式,線程安全,類裝載的時候就會被加載 * * @author <a href="mailto:[email protected]">menergy</a> * DateTime: 14-3-8 下午11:31 */ public class HungrySingleton { //只有一個實例 private static HungrySingleton instance = new HungrySingleton(); /** * 私有構造器控制實例數量 */ private HungrySingleton(){ } /** * 獲取實例 * @return */ public static HungrySingleton getInstance(){ return instance; } } |
第2節:volatile關鍵字實現單例模式(線程安全,延遲加載)
package com.mcc.core.designPattern.build.singleton; /** * volatile關鍵字實現單例模式,線程安全,延遲加載 * * valatile關鍵字會屏蔽虛擬機中的一些必要的優化,影響運行效率,非特殊要求一般不用。 * * @author <a href="mailto:[email protected]">menergy</a> * DateTime: 14-3-8 下午11:40 */ public class VolatileSingleton { //volatile關鍵字修飾,不會被本地線程緩存,多個線程能正確的處理該變量 private volatile static VolatileSingleton instance = null; /** * 私有構造器控制實現數量 */ private VolatileSingleton(){ } public static VolatileSingleton getInstance(){ if (instance == null){ //同步塊,線程安全 synchronized (VolatileSingleton.class){ if (instance == null){ instance = new VolatileSingleton(); } } } return instance; } } |
第3節:類級內部類實現單例模式(線程安全,延遲加載)
package com.mcc.core.designPattern.build.singleton; /** * 類級內部類單例模式,線程安全,延遲加載,推薦使用 * * @author <a href="mailto:[email protected]">menergy</a> * DateTime: 14-3-8 下午11:54 */ public class InnerclassSingleton { private static class SingletonHolder{ //靜態初始化,由JVM來保證線程安全 private static InnerclassSingleton instance = new InnerclassSingleton(); } /** * 私有構造器控制實例數量 */ private InnerclassSingleton(){ } /** * 全局訪問點 * @return */ public static InnerclassSingleton getInstance(){ return SingletonHolder.instance; } } |