項目中經常會遇到單例的情況。大部分的單例代碼都差不多像這樣定義: internal class SingletonOne { private static SingletonOne _singleton; private SingletonOne() { } public static Single... ...
項目中經常會遇到單例的情況。大部分的單例代碼都差不多像這樣定義:
internal class SingletonOne { private static SingletonOne _singleton; private SingletonOne() { } public static SingletonOne Instance { get { if (_singleton == null) { var instance = new SingletonOne(); Interlocked.CompareExchange(ref _singleton, instance, null); } return _singleton; } } }
但是很明顯的一個缺點是這個類只能用作單例。
最近看了NopCommerce對單例有個包裝。覺得有點新穎 給大家分享一下。
/// <summary> /// Provides access to all "singletons" stored by <see cref="Singleton{T}"/>. /// </summary> public class Singleton { static Singleton() { allSingletons = new Dictionary<Type, object>(); } static readonly IDictionary<Type, object> allSingletons; /// <summary>Dictionary of type to singleton instances.</summary> public static IDictionary<Type, object> AllSingletons { get { return allSingletons; } } }
public class Singleton<T> : Singleton { static T instance; /// <summary>The singleton instance for the specified type T. Only one instance (at the time) of this object for each type of T.</summary> public static T Instance { get { return instance; } set { instance = value; AllSingletons[typeof(T)] = value; } } }
比如定義了一個類, 那麼可以這樣使用
public class Fake { } Singleton<Fake>.Instance = new Fake();