C# 单例模式实现

C# 单例模式实现,第1张

概述Double-Checked Locking public class Singleton { private volatile static Singleton _instance = null; private static readonly object _locker = new object(); private S Double-Checked Locking
    public class Singleton    {        private volatile static Singleton _instance = null;        private static Readonly object _locker = new object();        private Singleton() { }        public static Singleton GetInstance()        {            if (_instance == null)            {                lock (_locker)                {                    if (_instance == null)                        _instance = new Singleton();                }            }            return _instance;        }    }
静态初始化
    public sealed class Singleton    {        private static Readonly Singleton _instance = new Singleton();        // 显示静态构造函数,告诉C#编译器不要将Type标记beforefIEldinit(这样就能够使程序在类的字段被引用时才会实例化)        static Singleton() { }        // 防止创建该类的默认实例        private Singleton() { }        public static Singleton Instance        {            get            {                return _instance;            }        }    }
延迟初始化
    public sealed class Singleton    {        private Singleton() { }        public static Singleton Instance { get { return nested._instance; } }        private class nested        {            static nested() { }            internal static Readonly Singleton _instance = new Singleton();        }    }
.Net 4‘s Lazy<T> type 
    public sealed class Singleton    {        private static Readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());        private Singleton() { }        public static Singleton Instance { get { return lazy.Value; } }    }

以上4中方式都是线程安全的单例实现代码,推荐使用Lazy<T>的方式简单且性能良好。

总结

以上是内存溢出为你收集整理的C# 单例模式实现全部内容,希望文章能够帮你解决C# 单例模式实现所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/1232564.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-06
下一篇2022-06-06

发表评论

登录后才能评论

评论列表(0条)

    保存