MapAssetPool.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using System;
  2. using System.Collections.Generic;
  3. namespace XGame.Framework.Map
  4. {
  5. internal class MapAssetPool
  6. {
  7. private Dictionary<Type, Stack<object>> _viewPool = new Dictionary<Type, Stack<object>>();
  8. /// <summary>
  9. /// 获取ReusableObject (需与Recycle成对)
  10. /// </summary>
  11. /// <typeparam name="T"></typeparam>
  12. /// <returns></returns>
  13. public TEntityView Acquire<TEntityView>() where TEntityView : class, IEntityView, new()
  14. {
  15. Type type = typeof(TEntityView);
  16. if (_viewPool.ContainsKey(type))
  17. {
  18. var stack = _viewPool[type];
  19. if (stack.Count > 0)
  20. return stack.Pop() as TEntityView;
  21. }
  22. return Activator.CreateInstance<TEntityView>();
  23. }
  24. ///// <summary>
  25. ///// 回收 (需与Acquire成对)
  26. ///// </summary>
  27. ///// <param name="obj"></param>
  28. //public void Recycle<TEntityView>(TEntityView obj) where TEntityView : class, IEntityView, new()
  29. //{
  30. // Recycle(obj);
  31. //}
  32. /// <summary>
  33. /// 回收 (需与Acquire成对)
  34. /// </summary>
  35. /// <param name="obj"></param>
  36. public void Recycle(IEntityView obj)
  37. {
  38. if (obj == null) return;
  39. var type = obj.GetType();
  40. if (!_viewPool.TryGetValue(type, out var stack))
  41. {
  42. stack = new Stack<object>();
  43. _viewPool.Add(type, stack);
  44. }
  45. obj.Clear();
  46. stack.Push(obj);
  47. }
  48. public void Clear()
  49. {
  50. _viewPool.Clear();
  51. }
  52. }
  53. }