A singleton implementation is constructed using the C #2.0 model and a reflection.
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 );
}
}
Easy to use. For example Class Foo
{
Private Foo () // Must declare, or assert will fail in the singleton class
{
}
Public Void Bar ()
{
}
}
Void Test ()
{
Singleton<Foo>. Instance (). Bar ();
}
You can even define a class as follows: Public Class Foo: Singleton < Foo >
{
Protected Foo () // Must declare
{
}
Public Void Bar ()
{
}
}
Void Test ()
{
Foo. instance (). Bar ();
}