NopCommerce中的单例

项目中经常会遇到单例的情况。大部分的单例代码都差不多像这样定义:

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();
上一篇:056_异常


下一篇:实验九--裸机LCD