using System; using System.Collections.Generic; namespace Framework { public class ObjectPool { private readonly Stack _stack = new Stack(); private readonly Func _createFunc; private readonly Action _resetAction; private readonly Action _destroyAction; public ObjectPool(Func createFunc, Action resetAction = null, Action 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(); } } }