(1)单例模式:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Net.Http.Headers; 5 using System.Runtime.InteropServices.WindowsRuntime; 6 using System.Text; 7 using System.Threading.Tasks; 8 9 namespace Singleton 10 { 11 public class Counter 12 { 13 public Counter() 14 { 15 Console.WriteLine("创建了Couter对像"); 16 } 17 18 public static Counter _counter; 19 private static readonly object lockobj = new object(); 20 /// <summary> 21 /// 止方法只能用于非多线程的情况 22 /// </summary> 23 //public static Counter Instance 24 //{ 25 // get 26 // { 27 // if (_counter == null) 28 // { 29 // _counter = new Counter(); 30 // } 31 // return _counter; 32 // } 33 //} 34 35 36 /// <summary> 37 /// 加锁,但是多线程中会带来性能问题,每一个都要先获取锁 38 /// </summary> 39 //public static Counter Instance 40 //{ 41 // get 42 // { 43 // lock (lockobj) 44 // { 45 // if (_counter == null) 46 // { 47 // _counter = new Counter(); 48 // } 49 // return _counter; 50 // } 51 // } 52 //} 53 54 /// <summary> 55 ///(1).加锁,在外面先判断再加锁,是正确的方式 56 /// </summary> 57 //public static Counter Instance 58 //{ 59 // get 60 // { 61 // if (_counter == null) 62 // { 63 // lock (lockobj) 64 // { 65 // if (_counter == null) 66 // { 67 // _counter = new Counter(); 68 // } 69 // return _counter; 70 // } 71 // } 72 // return _counter; 73 // } 74 //} 75 76 /// <summary> 77 ///(2).使用静态对象单例特性 78 ///// </summary> 79 //public static Counter Instance=new Counter(); 80 81 /// <summary> 82 ///(3).使用Lazy 懒加载 83 /// </summary> 84 public static Lazy<Counter> LazyInstance = new Lazy<Counter>(() => new Counter()); 85 86 public static readonly Counter Instance = LazyInstance.Value; 87 88 /// <summary> 89 ///(4).容器注册单例 如prism 90 /// </summary> 91 92 93 } 94 }
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Singleton 8 { 9 internal class Program 10 { 11 static void Main(string[] args) 12 { 13 14 var counter1 = Counter.Instance; 15 var counter2 = Counter.Instance; 16 17 for (int i = 0; i < 10; i++) 18 { 19 Task.Run(() => 20 { 21 var counter3 = Counter.Instance; 22 var counter4 = Counter.Instance; 23 }); 24 25 } 26 27 Console.Read(); 28 } 29 } 30 }