单例模式
1 //1、线程不安全 2 //public sealed class Singleton 3 //{ 4 // private static Singleton instance; //定义私有的静态全局变量保存改类的唯一实例 5 // private Singleton() { } 6 // public static Singleton GetInstance() 7 // { 8 // //如果该类没有被实例化,才去创建改实例 9 // return instance ?? (instance=new Singleton()); 10 // } 11 //} 12 13 14 //2、线程安全 15 //public sealed class Singleton 16 //{ 17 // private static Singleton instance = null; 18 // //创建静态只读的进程辅助对象 19 // private static readonly object _lock = new object(); 20 // Singleton() { } 21 // public static Singleton GetInstance() 22 // { 23 // lock (_lock) 24 // { 25 // return instance ?? (instance = new Singleton()); 26 // } 27 // } 28 //} 29 30 31 32 //3、线程安全 双重锁定 33 //public sealed class Singleton 34 //{ 35 // private static Singleton instance; 36 // private static object _lock = new object(); 37 // private Singleton() { } 38 // public static Singleton GetInstance() 39 // { 40 // if (instance == null)//实例为空时,才加锁创建 41 // { 42 // lock (_lock)//保证只有一个线程可以访问改语句块 43 // { 44 // instance = instance ?? (new Singleton()); 45 // } 46 // } 47 // return instance; 48 // } 49 //} 50 51 52 53 54 //4、线程安全 静态初始化 55 //public sealed class Singleton 56 //{ 57 // private static Singleton instance = new Singleton(); 58 // private Singleton() { } 59 // public static Singleton GetInstance() 60 // { 61 // return instance; 62 // } 63 //} 64 65 66 //5、延迟初始化,内部类 67 //public sealed class Singleton 68 //{ 69 // private Singleton() { } 70 // public static Singleton GetInstance() 71 // { 72 // return Nested.instance; 73 // } 74 // //初始化工作放到Nested类中的静态成员来完成 75 // private class Nested 76 // { 77 // static Nested() { } 78 // internal static readonly Singleton instance = new Singleton(); 79 // } 80 //} 81 82 83 //6、延迟初始化,线程安全 84 public sealed class Singleton 85 { 86 private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton()); 87 public static Singleton GetInstance() 88 { 89 return lazy.Value; 90 } 91 private Singleton() { } 92 }
每天学习一点点,每天进步一点点