ObjectPool.cs 1000 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System;
  2. using System.Collections.Generic;
  3. namespace ETHotfix
  4. {
  5. public class ObjectPool
  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. obj.IsFromPool = true;
  21. return obj;
  22. }
  23. obj = (Component)Activator.CreateInstance(type);
  24. return obj;
  25. }
  26. public T Fetch<T>() where T : Component
  27. {
  28. T t = (T)this.Fetch(typeof(T));
  29. t.IsFromPool = true;
  30. return t;
  31. }
  32. public void Recycle(Component obj)
  33. {
  34. Type type = obj.GetType();
  35. Queue<Component> queue;
  36. if (!this.dictionary.TryGetValue(type, out queue))
  37. {
  38. queue = new Queue<Component>();
  39. this.dictionary.Add(type, queue);
  40. }
  41. queue.Enqueue(obj);
  42. }
  43. }
  44. }