Pool.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. namespace UGUI.Collections
  5. {
  6. internal class Pool<T> where T : new()
  7. {
  8. private readonly Stack<T> _stack = new Stack<T>();
  9. private readonly Action<T> _actionOnGet;
  10. private readonly Action<T> _actionOnRecycle;
  11. public int count { get; private set; }
  12. public int activeCount { get { return count - inactiveCount; } }
  13. public int inactiveCount { get { return _stack.Count; } }
  14. public Pool(Action<T> actionOnGet, Action<T> actionOnRecycle)
  15. {
  16. _actionOnGet = actionOnGet;
  17. _actionOnRecycle = actionOnRecycle;
  18. }
  19. public T Get()
  20. {
  21. T element;
  22. if (_stack.Count == 0)
  23. {
  24. element = new T();
  25. count++;
  26. }
  27. else
  28. {
  29. element = _stack.Pop();
  30. }
  31. if (_actionOnGet != null)
  32. _actionOnGet(element);
  33. return element;
  34. }
  35. public void Recycle(T element)
  36. {
  37. if (_stack.Count > 0 && ReferenceEquals(_stack.Peek(), element))
  38. {
  39. throw new Exception("Internal error. Trying to destroy object that is already released to pool.");
  40. }
  41. if (_actionOnRecycle != null)
  42. {
  43. _actionOnRecycle(element);
  44. }
  45. _stack.Push(element);
  46. }
  47. public void Clear()
  48. {
  49. _stack.Clear();
  50. count = 0;
  51. }
  52. }
  53. }