单例模式

来源:互联网 发布:淘宝里的一元秒杀在哪 编辑:程序博客网 时间:2024/06/05 19:34

单例模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点。

多线程时,注意lock,双重锁定:double-check locking应延迟需求。

 

 

    class Program    {        static void Main(string[] args)        {            Singleton s1 = Singleton.GetInstance();            Singleton s2 = Singleton.GetInstance();            if (s1 == s2)            {                Console.WriteLine("Objects are the same instance");            }            Console.Read();        }    }    class Singleton    {        private static Singleton instance;        private static readonly object syncRoot = new object();        private Singleton()        {        }        public static Singleton GetInstance()        {            if (instance == null)            {                lock (syncRoot)                {                    if (instance == null)                    {                        instance = new Singleton();                    }                }            }            return instance;        }    }


 

0 0
原创粉丝点击