首页 > 代码库 > 单例模式

单例模式

三种实现单例的方式

主测试代码:

class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 10; i++)
            {
                Task task = Task.Factory.StartNew(() =>
                {
                    //Single s = Single.CreateSingle();
                    //Single_2 s = Single_2.CreateSingle();
                    Single_3 s = Single_3.instance;
                    s.Say();
                });
            }
            Console.ReadKey();
        }
    }

 

第一种:

技术分享
/// <summary>
    /// 简单写法:会出现线程安全问题
    /// </summary>
    public class Single
    {
        private static Single _single = null;
        static object obj = new object();
        private Single()
        {

        }

        public static Single CreateSingle()
        {
            if (_single==null)
            {
                Console.WriteLine("对象被初始化--{0}",System.Threading.Thread.CurrentThread.ManagedThreadId);
                _single = new Single();
            }
            return _single;
        }

        public void Say()
        {
            Console.WriteLine("执行say方法--{0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
        }
    }
View Code

第二种:

技术分享
/// <summary>
    /// 安全写法,加入锁
    /// </summary>
    public class Single_2
    {
        private static Single_2 _single = null;
        static object obj = new object();
        private Single_2()
        {

        }

        public static Single_2 CreateSingle()
        {
            if (_single == null)
            {
                lock (obj)
                {
                    if (_single == null)
                    {
                        Console.WriteLine("对象被初始化--{0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
                        _single = new Single_2();
                    }
                }
            }
            return _single;
        }

        public void Say()
        {
            Console.WriteLine("执行say方法--{0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
        }
    }
View Code

第三种:

技术分享
/// <summary>
    /// 精简写法
    /// </summary>
    public class Single_3
    {
        public static readonly Single_3 instance = new Single_3();
        private Single_3()
        {
            Console.WriteLine("对象被初始化--{0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
        }
        public void Say()
        {
            Console.WriteLine("执行say方法--{0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
        }
    }
View Code

 

单例模式