[关闭]
@xuxuzhaozhao 2019-03-29T03:38:03.000000Z 字数 1162 阅读 486

.NET中三种正确的单例写法

设计模式


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

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

  1. public class Singleton
  2. {
  3. Singleton() { }
  4. static readonly object obj = new object();
  5. static Singleton _instance;
  6. public static Singleton GetInstance(bool forceInit = false)
  7. {
  8. if (forceInit)
  9. {
  10. _instance = new Singleton();
  11. }
  12. if (_instance == null)
  13. {
  14. lock (obj)
  15. {
  16. if (_instance == null)
  17. {
  18. _instance = new Singleton();
  19. }
  20. }
  21. }
  22. return _instance;
  23. }
  24. }

二、静态内部类

  1. public class Singleton
  2. {
  3. Singleton() { }
  4. private static class SingletonInstance
  5. {
  6. public static Singleton Instance = new Singleton();
  7. }
  8. public static Singleton Instance => SingletonInstance.Instance;
  9. }

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

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

  1. //单纯的单例模式
  2. public sealed class Singleton
  3. {
  4. Singleton() { }
  5. static readonly Lazy<Singleton> lazySingleton
  6. = new Lazy<Singleton>(() => new Singleton());
  7. public static Singleton GetInstance => lazySingleton.Value;
  8. }
  9. //更新缓存的单例模式
  10. public sealed class Singleton
  11. {
  12. Singleton() { }
  13. static Lazy<Singleton> lazySingleton = new Lazy<Singleton>(() => new Singleton());
  14. public static Singleton GetInstance(bool forceInit = false)
  15. {
  16. if (forceInit)
  17. {
  18. lazySingleton = new Lazy<Singleton>(() => new Singleton());
  19. }
  20. return lazySingleton.Value;
  21. }
  22. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注