Home
Manage Your Code
Snippet: Singleton Factory (C#)
Title: Singleton Factory Language: C#
Description: http://www.codeplex.com/Super4Utils Views: 644
Author: Nip Nip Date Added: 3/6/2008
Copy Code  
1namespace Test
2{
3    // this is the class for which I want to maintain a single instance

4    public class MyClass
5    {
6        private MyClass()
7        {
8            // private constructor ensures that callers cannot instantiate an object using new()

9        }
10    }
11
12    // Singleton factory implementation

13    public static class Singleton<T> where T : class
14    {
15        // static constructor, runtime ensures thread safety

16        static Singleton()
17        {
18            // create the single instance of the type T using reflection

19            Instance = (T)Activator.CreateInstance(typeof(T), true);
20        }
21
22        // serve the single instance to callers

23        public static T Instance { private set; get; }
24    }
25
26    class Program
27    {
28        public static void Main()
29        {
30            // test

31            Console.WriteLine(Object.ReferenceEquals(Singleton<MyClass>.Instance, Singleton<MyClass>.Instance));
32        }
33    }
34}