Singleton3.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace SingletonPattern
  7. {
  8. /// <summary>
  9. /// 单例模式实现方式三:
  10. /// 锁机制,确保多线程只产生一个实例
  11. /// </summary>
  12. public class Singleton3
  13. {
  14. private static Singleton3 _instance;
  15. private static readonly object Locker =new object();
  16. private Singleton3() { }
  17. public static Singleton3 Instance()
  18. {
  19. //没有第一重 instance == null 的话,每一次有线程进入 GetInstance()时,均会执行锁定操作来实现线程同步,
  20. //非常耗费性能 增加第一重instance ==null 成立时的情况下执行一次锁定以实现线程同步
  21. if (_instance==null)
  22. {
  23. lock (Locker)
  24. {
  25. //Double-Check Locking 双重检查锁定
  26. if (_instance==null)
  27. {
  28. _instance = new Singleton3();
  29. }
  30. }
  31. }
  32. return _instance;
  33. }
  34. public void GetInfo()
  35. {
  36. Console.WriteLine(string.Format("I am {0}.",this.GetType().Name));
  37. }
  38. }
  39. }