zoukankan      html  css  js  c++  java
  • .NET 中三种正确的单例写法

    在企业应用开发中,会出现比较多的一种情况就是,读取大对象。这种情况多适用于单例模式,单例模式在C#中有很多种写法,错误或者线程不安全的写法我就不写了。现记录常用的三种写法。

    一、双重检查锁定【适用与作为缓存存在的单例模式】

    public class Singleton
    {
        Singleton() { }
        static readonly object obj = new object();
        static Singleton _instance;
    
        public static Singleton GetInstance(bool forceInit = false)
        {
            if (forceInit)
            {
                _instance = new Singleton();
            }
            if (_instance == null)
            {
                lock (obj)
                {
                    if (_instance == null)
                    {
                        _instance = new Singleton();
                    }
                }
            }
            return _instance;
        }
    }
    

    二、静态内部类

    public class Singleton
    {
        Singleton() { }
    
        private static class SingletonInstance
        {
            public static Singleton Instance = new Singleton();
        }
    
        public static Singleton Instance => SingletonInstance.Instance;
    }
    

    三、使用System.Lazy<T>延迟加载 【推荐】

    Lazy 对象初始化默认是线程安全的,在多线程环境下,第一个访问 Lazy 对象的 Value 属性的线程将初始化 Lazy 对象,以后访问的线程都将使用第一次初始化的数据。

    //单纯的单例模式
    public sealed class Singleton
    {
        Singleton() { }
    
        static readonly Lazy<Singleton> lazySingleton
            = new Lazy<Singleton>(() => new Singleton());
    
        public static Singleton GetInstance => lazySingleton.Value;
    }
    
    //更新缓存的单例模式
    public sealed class Singleton
    {
        Singleton() { }
        static Lazy<Singleton> lazySingleton = new Lazy<Singleton>(() => new Singleton());
    
        public static Singleton GetInstance(bool forceInit = false)
        {
            if (forceInit)
            {
                lazySingleton = new Lazy<Singleton>(() => new Singleton());
            }
            return lazySingleton.Value;
        }
    }
    
  • 相关阅读:
    CSU1018: Avatar
    ZOJ
    HDU—4463 Outlets 最小生成树
    查询文件中值所在的路径
    mysql语句查询时间检测
    phpmyadmin修改root密码
    检测Linux glibc幽灵漏洞和修补漏洞
    监控宝安装手册
    ubuntu安装环境软件全文档
    ubuntu mysql主从库的搭建
  • 原文地址:https://www.cnblogs.com/xuxuzhaozhao/p/10248483.html
Copyright © 2011-2022 走看看