GenericSingleton.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. /// </summary>
  11. /// <typeparam name="T"></typeparam>
  12. public class GenericSingleton<T> where T : class//,new ()
  13. {
  14. private static T instance;
  15. private static readonly object Locker = new object();
  16. public static T GetInstance()
  17. {
  18. //没有第一重 instance == null 的话,每一次有线程进入 GetInstance()时,均会执行锁定操作来实现线程同步,
  19. //非常耗费性能 增加第一重instance ==null 成立时的情况下执行一次锁定以实现线程同步
  20. if (instance == null)
  21. {
  22. //Double-Check Locking 双重检查锁定
  23. lock (Locker)
  24. {
  25. if (instance == null)
  26. {
  27. //instance = new T();
  28. //需要非公共的无参构造函数,不能使用new T() ,new不支持非公共的无参构造函数
  29. instance = Activator.CreateInstance(typeof(T), true) as T;//第二个参数防止异常:“没有为该对象定义无参数的构造函数。”
  30. }
  31. }
  32. }
  33. return instance;
  34. }
  35. public void GetInfo()
  36. {
  37. Console.WriteLine(string.Format("I am {0}.", this.GetType().Name));
  38. }
  39. }
  40. }