2011年6月8日 星期三

[C#] Generic Singleton Pattern

C# singleton pattern with generic.
Why need using generic singleton?
If we use an interface named ISingleton, and provide an Instance property, we must implement in all derived class.
Or we need to provide Instance property in all singleton class.
That is a trouble, so we use generic to solute it
Because singleton need provide private or protected constructor, so we can't use new T() in generic singleton pattern.
So we need to use reflection to call constructor.
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;
}
}
}
}

沒有留言:

張貼留言

Hello