C# 设计模式(1)单例模式

单例模式:

1. 程序只需要这个对象实列化一次.

2. 不能解决多线程并发问题

3. 主要应用于 数据库连接池、线程池、流水号生成器、配置文件读取、IOC容器实列

实现方法一(懒汉式)

    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 5; i++)
            {
                Task.Run(() =>
                {
                    Console.WriteLine($"HashCode is {Singleton.GetInstance().GetHashCode()}");
                });
            }

            Console.ReadLine();
        }
    }

    public class Singleton
    {
        private static Singleton _singleton;
        private static readonly object _lock = new object();
        private Singleton()
        {
            
        }

        public static Singleton GetInstance()
        {
            if(_singleton==null)
            {
                lock (_lock)
                {
                    if (_singleton == null)
                        _singleton = new Singleton();
                }
            }
            return _singleton;
        }
    }

 

 实现方法二:(饿汉式)

    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 5; i++)
            {
                Task.Run(() =>
                {
                    Console.WriteLine($"HashCode is {SingletonSecond.GetInstance().GetHashCode()}");
                });
            }
            Console.ReadLine();
        }
    }

    public class SingletonSecond
    {
        private static readonly SingletonSecond _singletonSecond;
        private SingletonSecond()
        {

        }

        static SingletonSecond()
        {
           _singletonSecond =  new SingletonSecond();
        }

        public static SingletonSecond GetInstance()
        {
            return _singletonSecond;
        }
    }

 

posted @ 2020-11-30 10:53  NiKaFace  阅读(245)  评论(0编辑  收藏  举报