diff --git a/Engine.Core/Helpers/Pool.cs b/Engine.Core/Helpers/Pool.cs new file mode 100644 index 0000000..b9f5c99 --- /dev/null +++ b/Engine.Core/Helpers/Pool.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; + +namespace Syntriax.Engine.Core; + +public class Pool +{ + private readonly Func factory; + private readonly Queue queue = new(); + + public T Get() + { + if (queue.TryDequeue(out T? result)) + return result; + + return factory(); + } + + public void Return(T item) + { + if (queue.Contains(item)) + return; + + queue.Enqueue(item); + } + + public Pool(Func factory, int initialCapacity = 1) + { + this.factory = factory; + for (int i = 0; i < initialCapacity; i++) + queue.Enqueue(factory()); + } +}