ObjectPool.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System;
  2. using System.Collections.Generic;
  3. namespace ETModel
  4. {
  5. public class ObjectPool: Component
  6. {
  7. private readonly Dictionary<Type, Queue<Component>> dictionary = new Dictionary<Type, Queue<Component>>();
  8. public Component Fetch(Type type)
  9. {
  10. Queue<Component> queue;
  11. if (!this.dictionary.TryGetValue(type, out queue))
  12. {
  13. queue = new Queue<Component>();
  14. this.dictionary.Add(type, queue);
  15. }
  16. Component obj;
  17. if (queue.Count > 0)
  18. {
  19. obj = queue.Dequeue();
  20. }
  21. else
  22. {
  23. obj = (Component)Activator.CreateInstance(type);
  24. }
  25. obj.IsFromPool = true;
  26. return obj;
  27. }
  28. public T Fetch<T>() where T: Component
  29. {
  30. T t = (T) this.Fetch(typeof(T));
  31. return t;
  32. }
  33. public void Recycle(Component obj)
  34. {
  35. obj.Parent = this;
  36. Type type = obj.GetType();
  37. Queue<Component> queue;
  38. if (!this.dictionary.TryGetValue(type, out queue))
  39. {
  40. queue = new Queue<Component>();
  41. this.dictionary.Add(type, queue);
  42. }
  43. queue.Enqueue(obj);
  44. }
  45. public void Clear()
  46. {
  47. foreach (var kv in this.dictionary)
  48. {
  49. foreach (Component component in kv.Value)
  50. {
  51. component.IsFromPool = false;
  52. component.Dispose();
  53. }
  54. }
  55. this.dictionary.Clear();
  56. }
  57. }
  58. }