Thursday, March 29, 2012

Design Pattern : Generic Singleton Class

Generic Class Object

public class GetInstance1<T> where T : class
    {
        private static object SyncRoot = new object();
        private static T instance = default(T);
        public static T Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (SyncRoot)
                    {
                        if (instance == null)
                        {
                            ConstructorInfo ci = typeof(T).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null);
                            if (ci == null) { throw new InvalidOperationException("Class must contain a private constructor"); }
                            instance = (T)ci.Invoke(null);
                        }
                    }
                }
                return instance;
            }
        }

Test Class
 public class MyTestClass
    {
        private MyTestClass() { }

        public string GetName()
        {

            return "Hi";
        }

    }

Consuming Class
 string strGetInstance1 = GetInstance1<MyTestClass>.Instance.GetName();

No comments:

Post a Comment