李虹霖

 

c#单例模式

using System;
using System.Collections.Generic;
using System.Text;

namespace 单例模式
{
    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;
        }

    }

    //public sealed class Singleton
    //{
    //    private static readonly Singleton instance = new Singleton();
    //    private Singleton() { }
    //    public static Singleton GetInstance()
    //    {
    //        return instance;
    //    }
    //}
}

 

posted on 2015-03-08 12:07  lol霖  阅读(165)  评论(0编辑  收藏  举报

导航