From d4efce48c362ef6d8f67fd14154676f13b93323b Mon Sep 17 00:00:00 2001 From: Harrison Deng Date: Sat, 11 Jul 2020 01:37:45 -0500 Subject: [PATCH] Added pooling system. --- .../Collections/Pooling/IPoolable.cs | 7 +++ .../Collections/Pooling/ObjectPool.cs | 45 +++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 src/SlatedGameToolkit.Framework/Utilities/Collections/Pooling/IPoolable.cs create mode 100644 src/SlatedGameToolkit.Framework/Utilities/Collections/Pooling/ObjectPool.cs diff --git a/src/SlatedGameToolkit.Framework/Utilities/Collections/Pooling/IPoolable.cs b/src/SlatedGameToolkit.Framework/Utilities/Collections/Pooling/IPoolable.cs new file mode 100644 index 0000000..8193d9d --- /dev/null +++ b/src/SlatedGameToolkit.Framework/Utilities/Collections/Pooling/IPoolable.cs @@ -0,0 +1,7 @@ +namespace SlatedGameToolkit.Framework.Utilities.Collections.Pooling +{ + public interface IPoolable + { + void Reset(); + } +} \ No newline at end of file diff --git a/src/SlatedGameToolkit.Framework/Utilities/Collections/Pooling/ObjectPool.cs b/src/SlatedGameToolkit.Framework/Utilities/Collections/Pooling/ObjectPool.cs new file mode 100644 index 0000000..60e3dc4 --- /dev/null +++ b/src/SlatedGameToolkit.Framework/Utilities/Collections/Pooling/ObjectPool.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; + +namespace SlatedGameToolkit.Framework.Utilities.Collections.Pooling +{ + public class ObjectPool where Poolable : IPoolable + { + public int Size { get; private set; } + public int Count { + get { + return pool.Count; + } + } + private Func creator; + private ConcurrentBag pool; + + public ObjectPool(Func creator, int size = 0, int initialCount = 0) { + this.creator = creator ?? throw new ArgumentNullException("creator"); + this.pool = new ConcurrentBag(); + this.Size = size; + CreateAmount(initialCount); + } + + public void CreateAmount(int amount) { + for (int i = 0; i < amount; i++) { + pool.Add(creator()); + } + } + + public Poolable Retrieve() { + if (pool.Count == 0) { + pool.Add(creator()); + } + Poolable result; + pool.TryTake(out result); + return result; + } + + public void Release(Poolable poolable) { + poolable.Reset(); + pool.Add(poolable); + } + } +} \ No newline at end of file