单例模式:简单来说,就是指类只能被初始化一次, 一般情况下单例类是sealed

单例模式的四种实现方式:

  1. 线程安全的创建对象的形式
    public sealed class Singleton
    {
        private static Singleton _singleton = null;
        private static object Singleton_Lock = new object();
        public static Singleton CreateInstance()
        {
            if (_singleton==null)
            {
                lock (Singleton_Lock)
                {
                    if (_singleton==null)
                    {
                        _singleton = new Singleton();
                    }
                }
            }
            return _singleton;
        }
    }

    双重if+锁的机制,保证线程安全,且只被实例化一次

  2. 静态属性形式
    public sealed class Singleton
    {
       
        private Singleton() { }
        private static readonly Singleton _singletonInstance = new Singleton();
        public static Singleton GetInstance {
            get {
                return _singletonInstance;
            }
        }
    }

    由CLR保证,在程序第一次使用该类之前被调用,而且只调用一次

  3. 静态构造函数形式
    public sealed class Singleton
    {
        private static Singleton _singleton = null;
        static Singleton()
        {
            _singleton = new Singleton();
        }
        public static Singleton CreateSingleton()
        {
            return _singleton;
        }
    }

    同样是由CLR保证,在程序第一次使用该类之前被调用,而且只调用一次。同静态变量一样, 它会随着程序运行, 就被实例化, 同静态变量一个道理。

  4. 懒加载的形式
    public sealed class Singleton
    {
        private Singleton() { }
        private static readonly Lazy<Singleton> lazySingleton = new Lazy<Singleton>(() => new Singleton());
        public static Singleton GetInstance {
            get {
                return lazySingleton.Value;
            }
        }
    }

    作为 .NET Framework 4.0 的一部分引入的惰性关键字为惰性初始化(即按需对象初始化)提供了内置支持。如果要使对象(如 Singleton)以延迟初始化,则只需将对象的类型(单例)传递给lazy 关键字

posted on 2021-11-09 12:33  菜鸟小辛  阅读(135)  评论(0编辑  收藏  举报