ObjectPool.cs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System;
  2. using System.Collections.Generic;
  3. using Model;
  4. namespace Hotfix
  5. {
  6. public class ObjectPool
  7. {
  8. private readonly Dictionary<Type, Queue<Disposer>> dictionary = new Dictionary<Type, Queue<Disposer>>();
  9. public Disposer Fetch(Type type)
  10. {
  11. Queue<Disposer> queue;
  12. if (!this.dictionary.TryGetValue(type, out queue))
  13. {
  14. queue = new Queue<Disposer>();
  15. this.dictionary.Add(type, queue);
  16. }
  17. Disposer obj;
  18. if (queue.Count > 0)
  19. {
  20. obj = queue.Dequeue();
  21. obj.Id = IdGenerater.GenerateId();
  22. return obj;
  23. }
  24. obj = (Disposer)Activator.CreateInstance(type);
  25. return obj;
  26. }
  27. public T Fetch<T>() where T: Disposer
  28. {
  29. return (T) this.Fetch(typeof(T));
  30. }
  31. public void Recycle(Disposer obj)
  32. {
  33. Type type = obj.GetType();
  34. Queue<Disposer> queue;
  35. if (!this.dictionary.TryGetValue(type, out queue))
  36. {
  37. queue = new Queue<Disposer>();
  38. this.dictionary.Add(type, queue);
  39. }
  40. queue.Enqueue(obj);
  41. }
  42. }
  43. }