五维思考

学习要加,骄傲要减,机会要乘,懒惰要除。 http://www.5dthink.cn

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

核心代码,线程安全

    class SingletonFactory<T> where T : new()
    {
        private static T uniqueInstance;
        private static readonly object locker = new object();
        public static T GetInstance()
        {
            if (uniqueInstance == null)
            {
                lock (locker)
                {
                    if (uniqueInstance == null) uniqueInstance = new T();
                }
            }
            return uniqueInstance;
        }
    }

测试类

    class Person
    {
        public string Name { get; set; }
    }

    class Cat
    {
        public string Name { get; set; }
    }

测试代码

        static void Main(string[] args)
        {
            var obj1 = SingletonFactory<Person>.GetInstance();
            obj1.Name = "张三";
            var obj2 = SingletonFactory<Person>.GetInstance();
            obj2.Name = "李四";
            Console.WriteLine($"obj1=obj2 :{ReferenceEquals(obj1, obj2)}");
            var obj3 = SingletonFactory<Cat>.GetInstance();
            obj3.Name = "咪咪";
            Console.WriteLine($"obj1=obj3 :{ReferenceEquals(obj1, obj3)}");
            Console.ReadKey();
        }

结果

posted on 2020-07-05 23:07  五维思考  阅读(799)  评论(0编辑  收藏  举报

QQ群:1. 全栈码农【346906288】2. VBA/VSTO【2660245】