Sunday, March 09, 2008

Singleton Factory in C#

    // this is the class for which
// I want to maintain a single instance
public class MyClass
{
private MyClass()
{
/* private constructor ensures that
callers cannot instantiate an
object using new() */
}
}

// Singleton factory implementation
public static class Singleton<T> where T : class
{
// static constructor,
//runtime ensures thread safety
static Singleton()
{
// create the single instance
// of the type T using reflection
Instance = (T)Activator.CreateInstance(
typeof(T),true);
}

// serve the single instance to callers
public static T Instance { private set; get; }
}

class Program
{
public static void Main()
{
// test
Console.WriteLine(
Object.ReferenceEquals(
Singleton<MyClass>.Instance,
Singleton<MyClass>.Instance));
}
}




via Cognitive Coding

No comments: