




















利用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();
}
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。