單例模式的代碼總結
阿新 • • 發佈:2017-09-19
單例 col 方法 turn 關鍵字 工廠 運行 靜態 工廠方法
懶漢式單例類
/** * 懶漢式單例類 * 懶漢式是典型的時間換空間 * @author MJ * */ public class LazySingleton { private static LazySingleton instance = null; // 私有構造方法 private LazySingleton() { } // 靜態工廠方法 public static synchronized LazySingleton getInstance() { if (instance == null) { instance= new LazySingleton(); } return instance; } }
餓漢式單例類
/** * 餓漢式單例類 * 餓漢式是典型的空間換時間 * @author MJ * */ public class EagerSingleton { private static EagerSingleton instance = new EagerSingleton(); /** * 私有構造方法 */ private EagerSingleton(){} //靜態工廠方法public static EagerSingleton getInstance() { return instance; } }
雙重檢查加鎖
/** * 雙重檢查加鎖 * 提示:由於volatile關鍵字可能會屏蔽掉虛擬機中一些必要的代碼優化,所以運行效率並不是很高。因此一般建議,沒有特別的需要,不要使用。 * 也就是說,雖然可以使用“雙重檢查加鎖”機制來實現線程安全的單例,但並不建議大量采用,可以根據情況來選用。 * * @author MJ * */ public class Singleton { private volatilestatic Singleton instance = null; private Singleton() { } // 靜態工廠方法 public static Singleton getInstance() { // 先檢查實例是否存在,如果不存在才進入下面的同步快 if (instance == null) { // 同步塊,線程安全的創建實例 synchronized (Singleton.class) { // 再次檢查實例是否存在,如果不存在才真正的創建實例 if (instance == null) { instance = new Singleton(); } } } return instance; } }
單例模式的代碼總結