01_单例模式

单例模式是一种常见的设计模式,用于确保一个类只有一个实例,并提供一个全局访问点。在单例模式中,类会提供一个静态方法来获取其唯一实例,如果该实例不存在则会创建一个新实例,否则返回已有的实例。

 public sealed class Counter
    {
        public Counter() 
        {
            CreateTime = DateTime.Now;
            Console.WriteLine($"实例化时间:{CreateTime}");
        }

        public DateTime CreateTime { get;private set; }
        private static Counter singleton = null;
        
        /* 只能适用单线程
        
        public static Counter GetSingleton()
        {
            if (singleton == null)
            {
                singleton = new Counter();
            }

            return singleton;
        }*/


        //第2种,适用多线程
        //public static Counter Instance = new Counter();

        private static readonly object locker = new object();
        //第3种, 加锁,能用,性能差
        public static Counter Singleton
        {
            get
            {
                lock (locker)
                {
                    if (singleton == null)
                    {
                        singleton = new Counter();
                    }

                    return singleton;
                }
            }
        }

        //第4种方案 双判断锁,加强性能
        public static Counter Singleton2
        {
            get
            {
                if (singleton == null)
                {
                    lock (locker)
                    {
                        if (singleton == null)
                        {
                            singleton = new Counter();
                        }                        
                    }
                }

                return singleton;

            }
        }

        //第5种 Lazy 懒加载
        public static Counter LazyInstance=> new Lazy<Counter>(() => new Counter()).Value;

    }

 

static void Main(string[] args)
        {
            //Counter counter1 = Counter.Singleton;
            //Counter counter2 = Counter.Singleton;

            
            for (int i = 0;i < 1000; i++)
            {
                Task.Factory.StartNew(() =>
                {
                    Counter counter1 = Counter.LazyInstance;
                    Counter counter2 = Counter.LazyInstance;
                });
            }
           

            Console.ReadKey();
        }

 

posted @ 2024-03-08 10:45  野码  阅读(30)  评论(0编辑  收藏  举报