ObjectPool.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using System;
  2. using System.Collections.Generic;
  3. namespace KYFramework
  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. private readonly Dictionary<Type, Queue<object>> pool = new Dictionary<Type, Queue<object>>();
  51. public T Fetch<T>() where T: class
  52. {
  53. return this.Fetch(typeof (T)) as T;
  54. }
  55. public object Fetch(Type type)
  56. {
  57. Queue<object> queue = null;
  58. if (!pool.TryGetValue(type, out queue))
  59. {
  60. return Activator.CreateInstance(type);
  61. }
  62. if (queue.Count == 0)
  63. {
  64. return Activator.CreateInstance(type);
  65. }
  66. return queue.Dequeue();
  67. }
  68. public void Recycle(object obj)
  69. {
  70. Type type = obj.GetType();
  71. Queue<object> queue = null;
  72. if (!pool.TryGetValue(type, out queue))
  73. {
  74. queue = new Queue<object>();
  75. pool.Add(type, queue);
  76. }
  77. // 一种对象最大为1000个
  78. if (queue.Count > 1000)
  79. {
  80. return;
  81. }
  82. queue.Enqueue(obj);
  83. }
  84. }
  85. }