.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;
    }
}

转载于:https://www.cnblogs.com/xuxuzhaozhao/p/10248483.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值