1. 餓漢式是線程安全的,在類創建的同時就已經創建好一個靜態的對象供系統使用,以后不在改變。
public class EagerSingleton { private static final EagerSingleton m_instance = new EagerSingleton(); /** * 私有的默認構造子 */ private EagerSingleton() { } /** * 靜態工廠方法 */ public static EagerSingleton getInstance() { return m_instance; } }
2.懶漢式如果在創建實例對象時不加上synchronized則會導致對對象的訪問不是線程安全的,但是我們可以改造一下。
public class LazySingleton { //聲明一個靜態鎖 private static readonly object lockHelper = new object(); //私有構造函數 private LazySingleton() { } public static LazySingleton instence = null; //靜態屬性 public static LazySingleton Instence { get { if (instence == null) { lock (lockHelper) { if (instence == null) { instence = new LazySingleton(); } } } return instence; } } }