using UnityEngine; namespace AibisDream.Kit { public class SafeObjectPool : Pool, ISingleton where T : IPoolable, new() { #region Singleton void ISingleton.OnSingletonInit() { } protected SafeObjectPool() { mFactory = new DefaultObjectFactory(); } public static SafeObjectPool Instance => SingletonProp>.Instance; public void Dispose() { SingletonProp>.Dispose(); } #endregion /// /// Init the specified maxCount and initCount. /// /// Max Cache count. /// Init Cache count. public void Init(int maxCount, int initCount) { MaxCacheCount = maxCount; if (maxCount > 0) { initCount = Mathf.Min(maxCount, initCount); } if (CurCount < initCount) { for (var i = CurCount; i < initCount; ++i) { Recycle(new T()); } } } /// /// Gets or sets the max cache count. /// /// The max cache count. public int MaxCacheCount { get { return mMaxCount; } set { mMaxCount = value; if (mCacheStack != null) { if (mMaxCount > 0) { if (mMaxCount < mCacheStack.Count) { int removeCount = mCacheStack.Count - mMaxCount; while (removeCount > 0) { mCacheStack.Pop(); --removeCount; } } } } } } /// /// Allocate T instance. /// public override T Allocate() { var result = base.Allocate(); result.IsRecycled = false; return result; } /// /// Recycle the T instance /// /// T. public override bool Recycle(T t) { if (t == null || t.IsRecycled) { return false; } if (mMaxCount > 0) { if (mCacheStack.Count >= mMaxCount) { t.OnRecycled(); return false; } } t.IsRecycled = true; t.OnRecycled(); mCacheStack.Push(t); return true; } } }