DataModule.cs 1.6 KB

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