MonoPool.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System;
  2. using System.Collections.Generic;
  3. namespace ET
  4. {
  5. public class MonoPool: IDisposable
  6. {
  7. private readonly Dictionary<Type, Queue<object>> pool = new Dictionary<Type, Queue<object>>();
  8. public static MonoPool Instance = new MonoPool();
  9. private MonoPool()
  10. {
  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. queue.Enqueue(obj);
  35. }
  36. public void Dispose()
  37. {
  38. this.pool.Clear();
  39. }
  40. }
  41. }