SingleBase.cs 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. using System;
  2. namespace Houdar.Core.Util.Common
  3. {
  4. /// <summary>
  5. /// 单例基类
  6. /// </summary>
  7. /// <typeparam name="T"></typeparam>
  8. public class SingleBase<T> where T : new()
  9. {
  10. // ReSharper disable once InconsistentNaming
  11. private static readonly T _instance;
  12. // ReSharper disable once StaticFieldInGenericType
  13. private static readonly object ObjLock = new object();
  14. /// <summary>
  15. /// 获取单例句柄
  16. /// </summary>
  17. public static T Instance { get { return _instance; } }
  18. static SingleBase()
  19. {
  20. if (_instance != null) return;
  21. lock (ObjLock)
  22. {
  23. if (_instance == null)
  24. {
  25. _instance = new T();
  26. }
  27. }
  28. }
  29. public SingleBase()
  30. {
  31. if (_instance != null)
  32. {
  33. throw new InvalidOperationException("单例模式设计,不允许重复实例化对象");
  34. }
  35. }
  36. }
  37. }