ObjectPool.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System;
  2. using System.Collections.Generic;
  3. namespace ET
  4. {
  5. public class ObjectPool: Singleton<ObjectPool>
  6. {
  7. private readonly Dictionary<Type, Queue<object>> pool = new Dictionary<Type, Queue<object>>();
  8. public T Fetch<T>() where T: class
  9. {
  10. return this.Fetch(typeof (T)) as T;
  11. }
  12. public object Fetch(Type type)
  13. {
  14. Queue<object> queue = null;
  15. if (!pool.TryGetValue(type, out queue))
  16. {
  17. return Activator.CreateInstance(type);
  18. }
  19. if (queue.Count == 0)
  20. {
  21. return Activator.CreateInstance(type);
  22. }
  23. return queue.Dequeue();
  24. }
  25. public void Recycle(object obj)
  26. {
  27. Type type = obj.GetType();
  28. Queue<object> queue = null;
  29. if (!pool.TryGetValue(type, out queue))
  30. {
  31. queue = new Queue<object>();
  32. pool.Add(type, queue);
  33. }
  34. // 一种对象最大为1000个
  35. /*if (queue.Count > 1000)
  36. {
  37. return;
  38. }*/
  39. queue.Enqueue(obj);
  40. }
  41. }
  42. }