1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- using System;
- using System.Collections.Generic;
- using XGame.Framework.Interfaces;
- namespace XGame.Framework.Data
- {
- internal class DataModule : IDataModule, IDisposable
- {
- #region 静态函数
- private static DataModule _instance;
- public static IDataModule Instance
- {
- get
- {
- if (_instance == null)
- {
- _instance = new DataModule();
- }
- return _instance;
- }
- }
- public static void Dispose()
- {
- (_instance as IDisposable)?.Dispose();
- _instance = null;
- }
- #endregion
- private Dictionary<Type, IData> _dataMap = new Dictionary<Type, IData>();
- TType IDataModule.GetOrAdd<TType>()
- {
- var type = typeof(TType);
- if (!_dataMap.TryGetValue(type, out var data))
- {
- data = Activator.CreateInstance<TType>();
- _dataMap.Add(type, data);
- (data as IInitialize)?.Initialize();
- }
- return data as TType;
- }
- void IDataModule.Remove<TType>()
- {
- var type = typeof(TType);
- if(_dataMap.TryGetValue(type, out var data))
- {
- (data as IDisposable)?.Dispose();
- _dataMap.Remove(type);
- }
- }
- void IDisposable.Dispose()
- {
- foreach (var item in _dataMap.Values)
- {
- (item as IDisposable)?.Dispose();
- }
- _dataMap.Clear();
- }
- }
- }
|