你們認爲這是一個通用的單身人士嗎?一個通用的單身人士
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爲Highlander名稱;-) – 2008-12-19 11:43:50
除非對鎖定對象使用volatile關鍵字,否則此鎖定技術會中斷。請參見[this](http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html) – 2011-03-03 11:12:04
精細問題codereview.stackexchange.com – MPelletier 2012-03-31 17:24:31