ObjectPool.cs 1.2 KB

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