ObjectPool.cs 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. /*
  2. #########
  3. ############
  4. #############
  5. ## ###########
  6. ### ###### #####
  7. ### ####### ####
  8. ### ########## ####
  9. #### ########### ####
  10. #### ########### #####
  11. ##### ### ######## #####
  12. ##### ### ######## ######
  13. ###### ### ########### ######
  14. ###### #### ############## ######
  15. ####### ##################### ######
  16. ####### ###################### ######
  17. ####### ###### ################# ######
  18. ####### ###### ###### ######### ######
  19. ####### ## ###### ###### ######
  20. ####### ###### ##### #####
  21. ###### ##### ##### ####
  22. ##### #### ##### ###
  23. ##### ### ### #
  24. ### ### ###
  25. ## ### ###
  26. __________#_______####_______####______________
  27. 我们的未来没有BUG
  28. * ==============================================================================
  29. * Filename: ObjectPool
  30. * Created: 2018/7/13 14:29:22
  31. * Author: エル・プサイ・コングリィ
  32. * Purpose:
  33. * ==============================================================================
  34. */
  35. /*
  36. * 对象池
  37. */
  38. #if UNITY_EDITOR || USE_LUA_PROFILER
  39. using System;
  40. using System.Collections.Generic;
  41. namespace MikuLuaProfiler
  42. {
  43. public class ObjectPool<T> where T : class, new()
  44. {
  45. public delegate T CreateFunc();
  46. public ObjectPool()
  47. {
  48. }
  49. public ObjectPool(int poolSize, CreateFunc createFunc = null, Action<T> resetAction = null)
  50. {
  51. Init(poolSize, createFunc, resetAction);
  52. }
  53. public T GetObject()
  54. {
  55. lock (this)
  56. {
  57. if (m_objStack.Count > 0)
  58. {
  59. T t = m_objStack.Pop();
  60. return t;
  61. }
  62. }
  63. return new T();
  64. }
  65. public void Init(int poolSize, CreateFunc createFunc = null, Action<T> resetAction = null)
  66. {
  67. m_objStack = new Stack<T>(poolSize);
  68. for (int i = 0; i < poolSize; i++)
  69. {
  70. T item = new T();
  71. m_objStack.Push(item);
  72. }
  73. }
  74. public void Store(T obj)
  75. {
  76. if (obj == null)
  77. return;
  78. lock (this)
  79. {
  80. m_objStack.Push(obj);
  81. }
  82. }
  83. // 少用,调用这个池的作用就没有了
  84. public void Clear()
  85. {
  86. if (m_objStack != null)
  87. m_objStack.Clear();
  88. }
  89. public int Count
  90. {
  91. get
  92. {
  93. if (m_objStack == null)
  94. return 0;
  95. return m_objStack.Count;
  96. }
  97. }
  98. public Stack<T>.Enumerator GetIter()
  99. {
  100. if (m_objStack == null)
  101. return new Stack<T>.Enumerator();
  102. return m_objStack.GetEnumerator();
  103. }
  104. private Stack<T> m_objStack = null;
  105. }
  106. }
  107. #endif