¿Qué piensan sobre esto para un singleton genérico?Un singleton genérico
using System;
using System.Reflection;
// Use like this
/*
public class Highlander : Singleton<Highlander>
{
private Highlander()
{
Console.WriteLine("There can be only one...");
}
}
*/
public class Singleton<T> 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);
}
}
}
}
+1 para el nombre Highlander ;-) –
Esta técnica de bloqueo se rompe a menos que se utilice una palabra clave volátil para el objeto de bloqueo. Ver [esto] (http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html) –
Pregunta buena para codereview.stackexchange.com – MPelletier