ObjectPool.cs 1.5 KB

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