利用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();
}

浙公网安备 33010602011771号