C# 单例模式

定义

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

要点

    一是某个类只能有一个实例;
    二是它必须自行创建这个实例;
    三是它必须自行向整个系统提供这个实例。

代码实现

  1. 懒汉模式 - 双重检查锁定模式(Double Checked Locking)
    public sealed class Singleton
    {
        private Singleton()
        {
        }

        private static volatile Singleton instance = null;
        private static readonly object _lock = new object();

        public static Singleton Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (_lock)
                    {
                        if (instance == null)
                        {
                            instance = new Singleton();
                        }
                    }
                }
                return instance;
            }
        }
    }
  1. 饿汉模式 - 静态成员
    public sealed class Singleton
    {
        private Singleton()
        {
        }

        static Singleton()
        {
        }

        private static readonly Singleton instance = new Singleton();

        public static Singleton Instance
        {
            get
            {
                return instance;
            }
        }
    }
  1. 懒汉模式 - 静态内部类
    public sealed class Singleton
    {
        public static Singleton Instance { get { return Nested.instance; } }

        private static class Nested
        {
            static Nested()
            {
            }

            internal static readonly Singleton instance = new Singleton();
        }
    }
  1. 懒汉模式 - Lazy 类型
    public sealed class Singleton
    {
        private Singleton()
        {
        }

        private static readonly Lazy<Singleton> lazy =new Lazy<Singleton>(() => new Singleton());

        public static Singleton Instance { get { return lazy.Value; } }
    }

相关资料

  1. https://design-patterns.readthedocs.io/zh_CN/latest/creational_patterns/singleton.html

  2. https://www.cnblogs.com/leolion/p/10241822.html