Added pooling system.
This commit is contained in:
parent
f339a33d3e
commit
d4efce48c3
@ -0,0 +1,7 @@
|
|||||||
|
namespace SlatedGameToolkit.Framework.Utilities.Collections.Pooling
|
||||||
|
{
|
||||||
|
public interface IPoolable
|
||||||
|
{
|
||||||
|
void Reset();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,45 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Concurrent;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace SlatedGameToolkit.Framework.Utilities.Collections.Pooling
|
||||||
|
{
|
||||||
|
public class ObjectPool <Poolable> where Poolable : IPoolable
|
||||||
|
{
|
||||||
|
public int Size { get; private set; }
|
||||||
|
public int Count {
|
||||||
|
get {
|
||||||
|
return pool.Count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private Func<Poolable> creator;
|
||||||
|
private ConcurrentBag<Poolable> pool;
|
||||||
|
|
||||||
|
public ObjectPool(Func<Poolable> creator, int size = 0, int initialCount = 0) {
|
||||||
|
this.creator = creator ?? throw new ArgumentNullException("creator");
|
||||||
|
this.pool = new ConcurrentBag<Poolable>();
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user