53 lines
1.3 KiB
C#
53 lines
1.3 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)
|
|
{
|
|
if (_resetAction != null)
|
|
{
|
|
_resetAction(element);
|
|
}
|
|
|
|
_stack.Push(element);
|
|
}
|
|
|
|
public void Destroy()
|
|
{
|
|
if (_destroyAction != null)
|
|
{
|
|
foreach (var element in _stack)
|
|
{
|
|
_destroyAction(element);
|
|
}
|
|
}
|
|
|
|
_stack.Clear();
|
|
}
|
|
}
|
|
} |