MessagePool.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System;
  2. using System.Collections.Generic;
  3. namespace KYFramework.Network
  4. {
  5. public class MessagePool
  6. {
  7. public static MessagePool Instance { get; } = new MessagePool();
  8. private readonly Dictionary<Type, Queue<object>> dictionary = new Dictionary<Type, Queue<object>>();
  9. public object Fetch(Type type)
  10. {
  11. Queue<object> queue;
  12. if (!this.dictionary.TryGetValue(type, out queue))
  13. {
  14. queue = new Queue<object>();
  15. this.dictionary.Add(type, queue);
  16. }
  17. object obj;
  18. if (queue.Count > 0)
  19. {
  20. obj = queue.Dequeue();
  21. }
  22. else
  23. {
  24. obj = Activator.CreateInstance(type);
  25. }
  26. return obj;
  27. }
  28. public T Fetch<T>() where T : class
  29. {
  30. T t = (T)this.Fetch(typeof(T));
  31. return t;
  32. }
  33. public void Recycle(object obj)
  34. {
  35. Type type = obj.GetType();
  36. Queue<object> queue;
  37. if (!this.dictionary.TryGetValue(type, out queue))
  38. {
  39. queue = new Queue<object>();
  40. this.dictionary.Add(type, queue);
  41. }
  42. queue.Enqueue(obj);
  43. }
  44. }
  45. }