using System; using System.Collections.Generic; namespace KYFramework.Network { public class MessagePool { public static MessagePool Instance { get; } = new MessagePool(); private readonly Dictionary> dictionary = new Dictionary>(); public object Fetch(Type type) { Queue queue; if (!this.dictionary.TryGetValue(type, out queue)) { queue = new Queue(); this.dictionary.Add(type, queue); } object obj; if (queue.Count > 0) { obj = queue.Dequeue(); } else { obj = Activator.CreateInstance(type); } return obj; } public T Fetch() where T : class { T t = (T)this.Fetch(typeof(T)); return t; } public void Recycle(object obj) { Type type = obj.GetType(); Queue queue; if (!this.dictionary.TryGetValue(type, out queue)) { queue = new Queue(); this.dictionary.Add(type, queue); } queue.Enqueue(obj); } } }