Newer
Older
DungeonShooting / DungeonShooting_Godot / src / framework / pool / ObjectPool.cs
  1.  
  2. using System.Collections.Generic;
  3.  
  4. /// <summary>
  5. /// 对象池,用于获取和回收常用对象,避免每次都创建一个新的
  6. /// </summary>
  7. public static class ObjectPool
  8. {
  9. private static Dictionary<string, Stack<IPoolItem>> _pool = new Dictionary<string, Stack<IPoolItem>>();
  10.  
  11. /// <summary>
  12. /// 回收一个对象
  13. /// </summary>
  14. public static void Reclaim(IPoolItem poolItem)
  15. {
  16. if (poolItem.IsRecycled)
  17. {
  18. return;
  19. }
  20. var logotype = poolItem.Logotype;
  21. if (!_pool.TryGetValue(logotype, out var poolItems))
  22. {
  23. poolItems = new Stack<IPoolItem>();
  24. _pool.Add(logotype, poolItems);
  25. }
  26.  
  27. poolItems.Push(poolItem);
  28. poolItem.IsRecycled = true;
  29. poolItem.OnReclaim();
  30. }
  31.  
  32. /// <summary>
  33. /// 根据标识从池中取出一个实例,如果没有该标识类型的实例,则返回null
  34. /// </summary>
  35. public static IPoolItem GetItem(string logotype)
  36. {
  37. if (_pool.TryGetValue(logotype, out var poolItems))
  38. {
  39. if (poolItems.Count > 0)
  40. {
  41. var poolItem = poolItems.Pop();
  42. poolItem.IsRecycled = false;
  43. poolItem.OnLeavePool();
  44. return poolItem;
  45. }
  46. }
  47.  
  48. return null;
  49. }
  50. /// <summary>
  51. /// 根据标识从池中取出一个实例,如果没有该标识类型的实例,则返回null
  52. /// </summary>
  53. public static T GetItem<T>(string logotype) where T : IPoolItem
  54. {
  55. return (T)GetItem(logotype);
  56. }
  57.  
  58. /// <summary>
  59. /// 销毁所有池中的物体
  60. /// </summary>
  61. public static void DisposeAllItem()
  62. {
  63. foreach (var keyValuePair in _pool)
  64. {
  65. var poolItems = keyValuePair.Value;
  66. while (poolItems.Count > 0)
  67. {
  68. var item = poolItems.Pop();
  69. item.Destroy();
  70. }
  71. }
  72. _pool.Clear();
  73. }
  74. }