Singleton.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using System;
  2. using System.Threading;
  3. #if COMBAT_SERVER
  4. using Common.Combat;
  5. #endif
  6. using Fort23.UTool;
  7. namespace Utility
  8. {
  9. public class Singleton<T> : IDisposable where T : new()
  10. {
  11. static object m_lock = new object();
  12. #if COMBAT_SERVER
  13. private static Map<int, T> _threadingInstance = new Map<int, T>();
  14. #endif
  15. #if !COMBAT_SERVER
  16. protected static T m_instance;
  17. public static T Instance
  18. {
  19. get
  20. {
  21. if (m_instance == null)
  22. {
  23. lock (m_lock)
  24. {
  25. if (m_instance == null)
  26. {
  27. m_instance = new T();
  28. }
  29. }
  30. }
  31. return m_instance;
  32. }
  33. set { m_instance = value; }
  34. }
  35. public virtual void Dispose()
  36. {
  37. ProDispose();
  38. Instance = (T) (object) null;
  39. }
  40. #else
  41. public static T Instance
  42. {
  43. get
  44. {
  45. int id = Thread.CurrentThread.ManagedThreadId;
  46. if (typeof(T) == typeof(ConfigComponent) || typeof(T) == typeof(CombatPersistenceData))
  47. {
  48. id = 100;
  49. }
  50. if (_threadingInstance.TryGetValue(id, out T VALUE))
  51. {
  52. return VALUE;
  53. }
  54. lock (_threadingInstance)
  55. {
  56. if (_threadingInstance.TryGetValue(id, out T VALUE2))
  57. {
  58. return VALUE2;
  59. }
  60. else
  61. {
  62. // LogTool.Log("新建示例"+id+"__"+typeof(T));
  63. T iInstance = new T();
  64. _threadingInstance.Add(id, iInstance);
  65. return iInstance;
  66. }
  67. }
  68. }
  69. }
  70. public virtual void Dispose()
  71. {
  72. ProDispose();
  73. lock (_threadingInstance)
  74. {
  75. int id = Thread.CurrentThread.ManagedThreadId;
  76. _threadingInstance.Remove(id);
  77. }
  78. }
  79. #endif
  80. protected virtual void ProDispose()
  81. {
  82. }
  83. }
  84. }