這個...... 大家應該熟的不能再熟了 蟲子就不班門弄斧了
private static object LockKey = new object(); private static T _Instance; public static T GetInstance() { return GetInstance(null); } public static T GetInstance(Func<T> onCreateInstance) { if (_Instance == null) { lock (LockKey) { if (_Instance == null) { try { if (onCreateInstance == null) _Instance = new T(); else _Instance = onCreateInstance(); } catch { _Instance = default(T); } } } } return _Instance; } public static T GetInstance(object lockKey, T instance, Func<T> onCreateInstance) { if (instance == null) { if (lockKey == null) lockKey = LockKey; lock (lockKey) { if (instance == null) { try { if (onCreateInstance == null) instance = new T(); else instance = onCreateInstance(); } catch { instance = default(T); } } } } return instance; }
直接總結:單例模式確保一個類只有一個執行個體,並提供一個全域訪問點
查看本欄目更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/Programming/project/
Author:cnblogs 熬夜的蟲子