patterncsharpMinor
A generic singleton
Viewed 0 times
genericsingletonstackoverflow
Problem
What do you think about this for a generic singleton?
using System;
using System.Reflection;
/* Use like this
public class Highlander : Singleton
{
private Highlander()
{
Console.WriteLine("There can be only one...");
}
}*/
public class Singleton where T : class
{
private static T instance;
private static object initLock = new object();
public static T GetInstance()
{
if (instance == null)
CreateInstance();
return instance;
}
private static void CreateInstance()
{
lock (initLock)
{
if (instance == null)
{
Type t = typeof(T);
// Ensure there are no public constructors...
ConstructorInfo[] ctors = t.GetConstructors();
if (ctors.Length > 0)
{
throw new InvalidOperationException(String.Format("
{0} has at least one accesible ctor making it impossible
to enforce singleton behaviour", t.Name));
}
// Create an instance via the private constructor
instance = (T)Activator.CreateInstance(t, true);
}
}
}
}Solution
Since we have .NET 4, we could make use of
Lazypublic class Singleton where T : class, new()
{
private Singleton() {}
private static readonly Lazy instance = new Lazy(() => new T());
public static T Instance { get { return instance.Value; } }
}Code Snippets
public class Singleton<T> where T : class, new()
{
private Singleton() {}
private static readonly Lazy<T> instance = new Lazy<T>(() => new T());
public static T Instance { get { return instance.Value; } }
}Context
StackExchange Code Review Q#10554, answer score: 6
Revisions (0)
No revisions yet.