@xuxuzhaozhao
2019-03-29T03:38:03.000000Z
字数 1162
阅读 571
设计模式
在企业应用开发中,会出现比较多的一种情况就是,读取大对象。这种情况多适用于单例模式,单例模式在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;}}