Newer
Older
DungeonShooting / DungeonShooting_Godot / src / framework / pool / ObjectPool.cs
@小李xl 小李xl on 2 Nov 2023 1 KB 完成对象池基础功能
  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. var logotype = poolItem.Logotype;
  17. if (!_pool.TryGetValue(logotype, out var poolItems))
  18. {
  19. poolItems = new Stack<IPoolItem>();
  20. _pool.Add(logotype, poolItems);
  21. }
  22.  
  23. poolItems.Push(poolItem);
  24. poolItem.IsRecycled = true;
  25. poolItem.OnReclaim();
  26. }
  27.  
  28. /// <summary>
  29. /// 根据标识从池中取出一个实例,如果没有该标识类型的实例,则返回null
  30. /// </summary>
  31. public static IPoolItem GetItem(string logotype)
  32. {
  33. if (_pool.TryGetValue(logotype, out var poolItems))
  34. {
  35. if (poolItems.Count > 0)
  36. {
  37. var poolItem = poolItems.Pop();
  38. poolItem.IsRecycled = false;
  39. poolItem.OnLeavePool();
  40. return poolItem;
  41. }
  42. }
  43.  
  44. return null;
  45. }
  46. /// <summary>
  47. /// 根据标识从池中取出一个实例,如果没有该标识类型的实例,则返回null
  48. /// </summary>
  49. public static T GetItem<T>(string logotype) where T : IPoolItem
  50. {
  51. return (T)GetItem(logotype);
  52. }
  53.  
  54. /// <summary>
  55. /// 销毁所有池中的物体
  56. /// </summary>
  57. public static void DisposeAllItem()
  58. {
  59. foreach (var keyValuePair in _pool)
  60. {
  61. var poolItems = keyValuePair.Value;
  62. while (poolItems.Count > 0)
  63. {
  64. var item = poolItems.Pop();
  65. item.Destroy();
  66. }
  67. }
  68. _pool.Clear();
  69. }
  70. }