首页 > 代码库 > Singleton 单例模板

Singleton 单例模板

    /// <summary>  
    /// 单例模板  
    /// </summary>  
    /// <typeparam name="T"></typeparam>  
    public class Singleton<T> where T : new()
    {
        protected static T _instance;
        private static readonly object _lockObj;

        static Singleton()
        {
            _lockObj = new object();
        }

        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_lockObj)
                    {
                        if (_instance == null)
                        {
                            //如果是引用类型创建一个T实例,如果是值类型返回值的默认值  
                            _instance = (default(T) == null) ? Activator.CreateInstance<T>() : default(T);
                        }
                    }
                }

                return _instance;
            }
        }
    }  

 

Singleton 单例模板