利用c#2.0的範型加上一點反射,構造了一個自認為不錯的Singleton實現.
public class Singleton<T>
{
protected Singleton()
{
//Assert class T don't have public constructor
//Assert class T have a private/protected parameterless constructor
}
protected static T _instance;
public static T Instance()
{
//Assert class T don't have public constructor
//Assert class T have a private/protected parameterless constructor
//Assert class T is not abstract and is not an interface
if (_instance == null)
{
_instance = (T)Activator.CreateInstance(typeof(T),true);//use reflection to create instance of T
}
return _instance;
}
public void Destroy()
{
_instance = default(T);
}
}
使用也很方便;例如class Foo
{
private Foo()//must declare,or assert will fail in the singleton class
{
}
public void Bar()
{
}
}
void Test()
{
Singleton<Foo>.Instance().Bar();
}
甚至可以這樣定義一個類:public class Foo : Singleton<Foo>
{
protected Foo()//must declare
{
}
public void Bar()
{
}
}
void Test()
{
Foo.Instance().Bar();
}