I created a proposal to the .Net team to add singleton generics to the core library. (http://ift.tt/1K8wKAc)
Below was my code as a example implementation. I am curious as to what other C# programmers think. Note, this uses Lazy from .Net 4.0 and later. One feature that is interesting is that the static instance property can be a base type, not just the actual type. This supports some use cases that just using one type parameter misses, and it still allows for the common case if T and TClass are the same.
Of course, this requires that TClass have a parameterless constructor. I believe that this is common enough in actual usage to merit consideration for addition to the core library.
I'd love to hear from the community. And hey, if you are wondering how to implement a Singleton in C#, the below is a good way to do it.
public class SingletonType<T, TClass> where TClass : T, new()
{
private static readonly Lazy<TClass> _instance =
new Lazy<TClass>(
() => new TClass(),
LazyThreadSafetyMode.None);
private SingletonType() { }
public static T Instance { get { return _instance.Value; } }
}
public class SingletonTypeThreadSafe<T, TClass> where TClass : T, new()
{
private static readonly Lazy<TClass> _instance =
new Lazy<TClass>(
() => new TClass(),
LazyThreadSafetyMode.ExecutionAndPublication);
private SingletonTypeThreadSafe() { }
public static T Instance { get { return _instance.Value; } }
}
Aucun commentaire:
Enregistrer un commentaire