NLDClient-yudde/ProjectNLD/Assets/Code/Scripts/Framework/ObjectPool.cs

50 lines
1.2 KiB
C#

using System;
using System.Collections.Generic;
namespace Framework
{
public class ObjectPool<T>
{
private readonly Stack<T> _stack = new Stack<T>();
private readonly Func<T> _createFunc;
private readonly Action<T> _resetAction;
private readonly Action<T> _destroyAction;
public ObjectPool(Func<T> createFunc, Action<T> resetAction = null, Action<T> destroyAction = null, int initCount = 0)
{
_createFunc = createFunc;
_resetAction = resetAction;
_destroyAction = destroyAction;
for (var i = 0; i < initCount; i++)
{
_stack.Push(_createFunc());
}
}
public T Get()
{
return _stack.Count == 0 ? _createFunc() : _stack.Pop();
}
public void Release(T element)
{
_resetAction?.Invoke(element);
_stack.Push(element);
}
public void Destroy()
{
if (_destroyAction != null)
{
foreach (var element in _stack)
{
_destroyAction(element);
}
}
_stack.Clear();
}
}
}