SimpleObjPool.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // -----------------------------------------------------------------------
  2. // <copyright file="SimpleObjPool.cs" company="AillieoTech">
  3. // Copyright (c) AillieoTech. All rights reserved.
  4. // </copyright>
  5. // -----------------------------------------------------------------------
  6. namespace TapSDK.UI.AillieoTech
  7. {
  8. using System;
  9. using System.Collections.Generic;
  10. public class SimpleObjPool<T>
  11. {
  12. private readonly Stack<T> stack;
  13. private readonly Func<T> ctor;
  14. private readonly Action<T> onRecycle;
  15. private int size;
  16. private int usedCount;
  17. public SimpleObjPool(int max = 7, Action<T> onRecycle = null, Func<T> ctor = null)
  18. {
  19. this.stack = new Stack<T>(max);
  20. this.size = max;
  21. this.onRecycle = onRecycle;
  22. this.ctor = ctor;
  23. }
  24. public T Get()
  25. {
  26. T item;
  27. if (this.stack.Count == 0)
  28. {
  29. if (this.ctor != null)
  30. {
  31. item = this.ctor();
  32. }
  33. else
  34. {
  35. item = Activator.CreateInstance<T>();
  36. }
  37. }
  38. else
  39. {
  40. item = this.stack.Pop();
  41. }
  42. this.usedCount++;
  43. return item;
  44. }
  45. public void Recycle(T item)
  46. {
  47. if (this.onRecycle != null)
  48. {
  49. this.onRecycle.Invoke(item);
  50. }
  51. if (this.stack.Count < this.size)
  52. {
  53. this.stack.Push(item);
  54. }
  55. this.usedCount--;
  56. }
  57. public void Purge()
  58. {
  59. // TODO
  60. }
  61. public override string ToString()
  62. {
  63. return $"SimpleObjPool: item=[{typeof(T)}], inUse=[{this.usedCount}], restInPool=[{this.stack.Count}/{this.size}] ";
  64. }
  65. }
  66. }