using System; using UnityEngine; using System.Reflection; using System.Collections.Generic; namespace SK.Framework { public static class ObjectPool { /// /// 从对象池中获取实例 /// /// 对象类型 /// 对象实例 public static T Allocate() where T : IPoolable, new() { return ObjectPool.Instance.Allocate(); } /// /// 回收对象 /// /// 对象类型 /// 回收对象实例 /// 回收成功返回true 否则返回false public static bool Recycle(T t) where T : IPoolable, new() { return ObjectPool.Instance.Recycle(t); } /// /// 释放对象池 /// /// 对象类型 public static void Release() where T : IPoolable, new() { ObjectPool.Instance.Release(); } /// /// 设置对象池缓存数量上限 /// /// 对象类型 /// 缓存数量上限 public static void SetMaxCacheCount(int maxCacheCount) where T : IPoolable, new() { ObjectPool.Instance.MaxCacheCount = maxCacheCount; } } public class ObjectPool : IObjectPool where T : IPoolable, new() { private static ObjectPool instance; //对象池缓存数量上限 默认9 private int maxCacheCount = 9; //对象池 private readonly Stack pool = new Stack(); public static ObjectPool Instance { get { if (null == instance) { var ctors = typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.Public); var index = Array.FindIndex(ctors, m => m.GetParameters().Length == 0); if (index == -1) { Debug.LogError($"{typeof(ObjectPool)} 类型不具有公有无参构造函数."); } else { instance = Activator.CreateInstance>(); } } return instance; } } /// /// 当前池中缓存的数量 /// public int CurrentCacheCount { get { return pool.Count; } } /// /// 缓存数量上限 /// public int MaxCacheCount { get { return maxCacheCount; } set { if (maxCacheCount != value) { maxCacheCount = value; if (maxCacheCount > 0 && maxCacheCount < pool.Count) { int removeCount = pool.Count - maxCacheCount; while (removeCount > 0) { pool.Pop(); removeCount--; } } } } } /// /// 获取实例 /// /// 对象实例 public T Allocate() { //若对象池中有缓存则从对象池中获取 T retT = pool.Count > 0 ? pool.Pop() : new T(); retT.IsRecycled = false; return retT; } /// /// 回收对象 /// /// 回收对象实例 /// 回收成功返回true 否则返回false public bool Recycle(T t) { if (null == t || t.IsRecycled) return false; t.IsRecycled = true; t.OnRecycled(); //若未达到缓存数量上限 放入池中 if (pool.Count < maxCacheCount) { pool.Push(t); } return true; } /// /// 释放对象池 /// public void Release() { pool.Clear(); instance = null; } } }