ObjectPool.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. using System;
  2. using System.Collections.Generic;
  3. namespace ETModel
  4. {
  5. public class ComponentQueue: Component
  6. {
  7. public string TypeName { get; }
  8. private readonly Queue<Component> queue = new Queue<Component>();
  9. public ComponentQueue(string typeName)
  10. {
  11. this.TypeName = typeName;
  12. }
  13. public void Enqueue(Component component)
  14. {
  15. component.Parent = this;
  16. this.queue.Enqueue(component);
  17. }
  18. public Component Dequeue()
  19. {
  20. return this.queue.Dequeue();
  21. }
  22. public Component Peek()
  23. {
  24. return this.queue.Peek();
  25. }
  26. public int Count
  27. {
  28. get
  29. {
  30. return this.queue.Count;
  31. }
  32. }
  33. public override void Dispose()
  34. {
  35. if (this.IsDisposed)
  36. {
  37. return;
  38. }
  39. base.Dispose();
  40. while (this.queue.Count > 0)
  41. {
  42. Component component = this.queue.Dequeue();
  43. component.IsFromPool = false;
  44. component.Dispose();
  45. }
  46. }
  47. }
  48. public class ObjectPool: Component
  49. {
  50. public string Name { get; set; }
  51. private readonly Dictionary<Type, ComponentQueue> dictionary = new Dictionary<Type, ComponentQueue>();
  52. public Component Fetch(Type type)
  53. {
  54. Component obj;
  55. if (!this.dictionary.TryGetValue(type, out ComponentQueue queue))
  56. {
  57. obj = (Component)Activator.CreateInstance(type);
  58. }
  59. else if (queue.Count == 0)
  60. {
  61. obj = (Component)Activator.CreateInstance(type);
  62. }
  63. else
  64. {
  65. obj = queue.Dequeue();
  66. }
  67. obj.IsFromPool = true;
  68. return obj;
  69. }
  70. public T Fetch<T>() where T: Component
  71. {
  72. T t = (T) this.Fetch(typeof(T));
  73. return t;
  74. }
  75. public void Recycle(Component obj)
  76. {
  77. obj.Parent = this;
  78. Type type = obj.GetType();
  79. ComponentQueue queue;
  80. if (!this.dictionary.TryGetValue(type, out queue))
  81. {
  82. queue = new ComponentQueue(type.Name);
  83. queue.Parent = this;
  84. #if !SERVER
  85. queue.GameObject.name = $"{type.Name}s";
  86. #endif
  87. this.dictionary.Add(type, queue);
  88. }
  89. queue.Enqueue(obj);
  90. }
  91. public void Clear()
  92. {
  93. foreach (var kv in this.dictionary)
  94. {
  95. kv.Value.IsFromPool = false;
  96. kv.Value.Dispose();
  97. }
  98. this.dictionary.Clear();
  99. }
  100. }
  101. }