/* * 基础对象池 */ using System; using System.Collections.Generic; namespace AibisDream.Kit { public abstract class Pool : IPool { #region ICountObserverable /// /// Gets the current count. /// /// The current count. public int CurCount => mCacheStack.Count; #endregion protected IObjectFactory mFactory; public void SetObjectFactory(IObjectFactory factory) { mFactory = factory; } public void SetFactoryMethod(Func factoryMethod) { mFactory = new CustomObjectFactory(factoryMethod); } /// /// 存储相关数据的栈 /// protected readonly Stack mCacheStack = new Stack(); public void Clear(Action onClearItem = null) { if (onClearItem != null) { foreach (var poolObject in mCacheStack) { onClearItem(poolObject); } } mCacheStack.Clear(); } /// /// default is 5 /// protected int mMaxCount = 12; public virtual T Allocate() { return mCacheStack.Count == 0 ? mFactory.Create() : mCacheStack.Pop(); } public abstract bool Recycle(T obj); } }