欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

设计模式学习--Singleton泛型类

程序员文章站 2024-03-15 11:01:17
...
    /// <summary>
    /// Singleton泛型类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public sealed class Singleton<T> where T : new()
    {
        private static T instance = new T();

        private static object lockHelper = new object();

        /// <summary>
        /// 构造函数
        /// </summary>
        private Singleton()
        { }

        /// <summary>
        /// 获取实例
        /// </summary>
        /// <param name="value"></param>
        public static T GetInstance()
        {
            if (instance == null)
            {
                lock (lockHelper)
                {
                    if (instance == null)
                    {
                        instance = new T();
                    }
                }
            }

            return instance;
        }      

    }