Program.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. namespace SingletonPattern
  9. {
  10. class Program
  11. {
  12. static void Main(string[] args)
  13. {
  14. Console.WriteLine("单例模式:");
  15. TestStaticSingleton();
  16. TestLasyInitialSingleton();
  17. TestGenericSingleton();
  18. TestDoubleLockSingleton();
  19. }
  20. private static void TestStaticSingleton()
  21. {
  22. Console.WriteLine("静态变量初始化实例");
  23. Singleton1 singleton1 = Singleton1.Instance();
  24. singleton1.GetInfo();
  25. Console.ReadLine();
  26. }
  27. private static void TestLasyInitialSingleton()
  28. {
  29. Console.WriteLine("延迟初始化实例");
  30. Singleton2 singleton2 = Singleton2.Instance();
  31. singleton2.GetInfo();
  32. singleton2.Reset();
  33. Console.ReadLine();
  34. }
  35. private static void TestDoubleLockSingleton()
  36. {
  37. Console.WriteLine("锁机制确保多线程只产生一个实例");
  38. for (int i = 0; i < 2; i++)
  39. {
  40. Thread thread=new Thread(ExecuteInForeground);
  41. thread.Start();
  42. }
  43. }
  44. private static void ExecuteInForeground()
  45. {
  46. Console.WriteLine("Thread {0}: {1}, Priority {2}",
  47. Thread.CurrentThread.ManagedThreadId,
  48. Thread.CurrentThread.ThreadState,
  49. Thread.CurrentThread.Priority);
  50. Singleton3 singleton3 =Singleton3.Instance();
  51. singleton3.GetInfo();
  52. Console.WriteLine(singleton3.GetHashCode());
  53. }
  54. private static void TestGenericSingleton()
  55. {
  56. Console.WriteLine("泛型单例模式:");
  57. Singleton4 instance = GenericSingleton<Singleton4>.GetInstance();
  58. instance.GetInfo();
  59. var singleton4 = Singleton4.Instance;
  60. singleton4.GetInfo();
  61. Console.ReadLine();
  62. }
  63. }
  64. }