Unity 框架

ReferencePool.cs 1.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace TFramework
  5. {
  6. public class ReferencePool
  7. {
  8. private Queue<IReference> _referencePool;
  9. private int _capacity = 100;
  10. public ReferencePool(int capacity)
  11. {
  12. _capacity = capacity;
  13. _referencePool = new Queue<IReference>(_capacity);
  14. }
  15. /// <summary>
  16. /// 引用数量
  17. /// </summary>
  18. public int Count => _referencePool.Count;
  19. /// <summary>
  20. /// 生成引用
  21. /// </summary>
  22. /// <returns></returns>
  23. public T Spawn<T>() where T : class, IReference, new() => Count > 0 ? _referencePool.Dequeue() as T : new T();
  24. /// <summary>
  25. /// 回收引用
  26. /// </summary>
  27. /// <param name="refe"></param>
  28. public void Recycle<T>(T refe) where T : class, IReference, new()
  29. {
  30. if (Count >= _capacity)
  31. refe = null;
  32. else
  33. {
  34. refe.Reset();
  35. _referencePool.Enqueue(refe);
  36. }
  37. }
  38. /// <summary>
  39. /// 清空所有引用
  40. /// </summary>
  41. public void Clear() => _referencePool.Clear();
  42. }
  43. }