Skip to content

Instantly share code, notes, and snippets.

@profexorgeek
Last active June 11, 2019 21:37
Show Gist options
  • Save profexorgeek/25f30312d013dfaef08041cca8512d98 to your computer and use it in GitHub Desktop.
Save profexorgeek/25f30312d013dfaef08041cca8512d98 to your computer and use it in GitHub Desktop.
Generic factory capable of instantiating and pooling a list of entity objects.
using FlatRedBall.Graphics;
using FlatRedBall.Performance;
using System;
using System.Linq;
namespace MasteroidPE.Factories
{
public class Factory<T> where T : IPoolable, IDestroyable, new()
{
PoolList<T> pool = new PoolList<T>();
bool initialized = false;
public void Initialize(int poolSize)
{
for(var i = 0; i < poolSize; i++)
{
T item = new T();
pool.AddToPool(item);
}
initialized = true;
}
public virtual T CreateItem()
{
if(!initialized)
{
throw new Exception("This factory has not been initialized!");
}
if(!pool.HasAnyUnusedItems)
{
throw new Exception("Pool is out of objects. Pool size too small!");
}
var item = pool.GetNextAvailable();
return item;
}
public virtual void ReleaseItem(T item)
{
if(pool.Contains(item))
{
pool.MakeUnused(item);
}
}
public void Destroy()
{
foreach(var item in pool)
{
item.Destroy();
}
pool.MakeAllUnused();
pool.Clear();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment