C# 单例模式实现
发布时间:2020-12-15 22:38:35 所属栏目:百科 来源:网络整理
导读: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 == n
Double-Checked Lockingpublic 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>的方式简单且性能良好。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |