CObjectPool.cs 2.9 KB

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