ObjectPool.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. T t = (T) this.Fetch(typeof(T));
  44. t.IsFromPool = true;
  45. return t;
  46. }
  47. public void Recycle(Disposer obj)
  48. {
  49. Type type = obj.GetType();
  50. EQueue<Disposer> queue;
  51. if (!this.dictionary.TryGetValue(type, out queue))
  52. {
  53. queue = new EQueue<Disposer>();
  54. this.dictionary.Add(type, queue);
  55. }
  56. queue.Enqueue(obj);
  57. }
  58. }
  59. }