publicclass Singleton<T> { protected Singleton() { //Assert class T don't have public constructor //Assert class T have a private/protected parameterless constructor } protectedstatic T _instance; publicstatic 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; } publicvoid Destroy() { _instance =default(T); } }
使用也很方便;例如
class Foo { private Foo()//must declare,or assert will fail in the singleton class { } publicvoid Bar() { } } void Test() { Singleton<Foo>.Instance().Bar(); }