项目中经常会遇到单例的情况。大部分的单例代码都差不多像这样定义:
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对单例有个包装。觉得有点新颖 给大家分享一下。
///
/// Provides access to all "singletons" stored by .
///
public class Singleton
{
static Singleton()
{
allSingletons = new Dictionaryobject>();
}
static readonly IDictionaryobject> allSingletons;
/// Dictionary of type to singleton instances.
public static IDictionaryobject> AllSingletons
{
get { return allSingletons; }
}
}
public class Singleton : Singleton
{
static T instance;
/// The singleton instance for the specified type T. Only one instance (at the time) of this object for each type of T.
public static T Instance
{
get { return instance; }
set
{
instance = value;
AllSingletons[typeof(T)] = value;
}
}
}
比如定义了一个类, 那么可以这样使用
public class Fake
{
}
Singleton.Instance = new Fake();
Original: https://www.cnblogs.com/VectorZhang/p/5366812.html
Author: 禅宗花园…迷失的佛
Title: NopCommerce中的单例
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/572584/
转载文章受原作者版权保护。转载请注明原作者出处!