2011年6月8日 星期三

[C#] Generic Singleton Pattern

這是一個利用泛型實踐單例的範例

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace DesignPattern
{
public class TSingleton<T> where T : class
{
static object SyncRoot = new object();
static T instance;
public static readonly Type[] EmptyTypes = new Type[0];
public static T Instance
{
get
{
if (instance == null)
{
lock (SyncRoot)
{
if (instance == null)
{
ConstructorInfo ci = typeof(T).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, EmptyTypes, null);
if (ci == null) { throw new InvalidOperationException("class must contain a private constructor"); }
instance = (T)ci.Invoke(null);
//instance = Activator.CreateInstance(typeof(T)) as T;
}
}
}
return instance;
}
}
}
}

沒有留言:

張貼留言

嘎嘎嘎