DataModule.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System;
  2. using System.Collections.Generic;
  3. namespace XGame.Framework.Data
  4. {
  5. internal class DataModule : IDataModule, IDisposable
  6. {
  7. #region 静态函数
  8. private static DataModule _instance;
  9. public static IDataModule Instance
  10. {
  11. get
  12. {
  13. if (_instance == null)
  14. {
  15. _instance = new DataModule();
  16. }
  17. return _instance;
  18. }
  19. }
  20. public static void Dispose()
  21. {
  22. (_instance as IDisposable)?.Dispose();
  23. _instance = null;
  24. }
  25. #endregion
  26. private Dictionary<Type, IData> _dataMap = new Dictionary<Type, IData>();
  27. TType IDataModule.GetOrAdd<TType>()
  28. {
  29. var type = typeof(TType);
  30. if (!_dataMap.TryGetValue(type, out var data))
  31. {
  32. data = Activator.CreateInstance<TType>();
  33. _dataMap.Add(type, data);
  34. }
  35. return data as TType;
  36. }
  37. void IDataModule.Remove<TType>()
  38. {
  39. var type = typeof(TType);
  40. if(_dataMap.TryGetValue(type, out var data))
  41. {
  42. (data as IDisposable)?.Dispose();
  43. _dataMap.Remove(type);
  44. }
  45. }
  46. void IDisposable.Dispose()
  47. {
  48. foreach (var item in _dataMap.Values)
  49. {
  50. (item as IDisposable)?.Dispose();
  51. }
  52. _dataMap.Clear();
  53. }
  54. }
  55. }