Generic Singleton pattern

namespace SingletonPattern
{
    /// <summary>
    /// SingletonBase with Generic constraints with class (Reference type) ,new T must have a public parameterless constructor .
    /// with new constraints that the type can't be abstract.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class SingletonBase<T> where T : class ,new()
    {
        private static T instance;

        private static object lockingObject = new object();
        public static T Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (lockingObject)
                    {
                        if (instance == null)
                        {
                            instance = new T();
                        }
                    }
                }
                return instance;
            }
        }
    }
}

  

Person person = SingletonBase<Person>.Instance;
Woman woman = SingletonBase<Woman>.Instance;
Woman woman1 = SingletonBase<Woman>.Instance;

 

posted @ 2014-07-12 23:38  penney  阅读(86)  评论(0)    收藏  举报