ObjectPool.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System;
  2. using System.Collections.Generic;
  3. namespace Model
  4. {
  5. public class ObjectPool
  6. {
  7. private static ObjectPool instance;
  8. public static ObjectPool Instance
  9. {
  10. get
  11. {
  12. return instance ?? new ObjectPool();
  13. }
  14. }
  15. private readonly Dictionary<Type, EQueue<Disposer>> dictionary = new Dictionary<Type, EQueue<Disposer>>();
  16. private ObjectPool()
  17. {
  18. }
  19. public static void Close()
  20. {
  21. instance = null;
  22. }
  23. public Disposer Fetch(Type type)
  24. {
  25. EQueue<Disposer> queue;
  26. if (!this.dictionary.TryGetValue(type, out queue))
  27. {
  28. queue = new EQueue<Disposer>();
  29. this.dictionary.Add(type, queue);
  30. }
  31. Disposer obj;
  32. if (queue.Count > 0)
  33. {
  34. obj = queue.Dequeue();
  35. obj.Id = IdGenerater.GenerateId();
  36. return obj;
  37. }
  38. obj = (Disposer)Activator.CreateInstance(type);
  39. return obj;
  40. }
  41. public T Fetch<T>() where T: Disposer
  42. {
  43. return (T) this.Fetch(typeof(T));
  44. }
  45. public void Recycle(Disposer obj)
  46. {
  47. Type type = obj.GetType();
  48. EQueue<Disposer> queue;
  49. if (!this.dictionary.TryGetValue(type, out queue))
  50. {
  51. queue = new EQueue<Disposer>();
  52. }
  53. queue.Enqueue(obj);
  54. }
  55. }
  56. }