C# 单例模式

        #region Singleton
        class Singleton
        {
            private static Singleton singleton;
            private static object lockObj = new object();
            private Singleton()
            {
            }
            public static Singleton GetInstance()
            {
                if (singleton == null)
                {
                    lock (lockObj)
                    {
                        if (singleton == null)
                        {
                            singleton = new Singleton();
                        }
                    }
                }
                return singleton;
            }
        }
        static void SingletonTest()
        {
            Singleton s1 = Singleton.GetInstance();
            Singleton s2 = Singleton.GetInstance();
            if (s1 == s2)
            {
                Console.WriteLine("The same instance");
            }
        }
        #endregion   

 

posted @ 2017-08-20 16:44  落花流水Zxxxx  阅读(124)  评论(0编辑  收藏  举报