add ObjectPools helper to manage multiple pools for different types automatically

This commit is contained in:
Gered 2013-08-22 10:39:28 -04:00
parent 4d49304ec4
commit d4b861dd58
2 changed files with 55 additions and 0 deletions

View file

@ -140,6 +140,7 @@
<Compile Include="Support\ObjectPool.cs" /> <Compile Include="Support\ObjectPool.cs" />
<Compile Include="Support\IPoolable.cs" /> <Compile Include="Support\IPoolable.cs" />
<Compile Include="Support\BasicObjectPool.cs" /> <Compile Include="Support\BasicObjectPool.cs" />
<Compile Include="Support\ObjectPools.cs" />
</ItemGroup> </ItemGroup>
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\Portable\$(TargetFrameworkVersion)\Microsoft.Portable.CSharp.targets" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\Portable\$(TargetFrameworkVersion)\Microsoft.Portable.CSharp.targets" />
<ItemGroup> <ItemGroup>

View file

@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Blarg.GameFramework.Support
{
public static class ObjectPools
{
const int INITIAL_CAPACITY = 100;
class ObjectObjectPool : ObjectPool<Object>
{
Type _type;
public ObjectObjectPool(Type type)
: base(INITIAL_CAPACITY)
{
_type = type;
}
protected override object Allocate()
{
return Activator.CreateInstance(_type);
}
}
static Dictionary<Type, ObjectObjectPool> _pools = new Dictionary<Type, ObjectObjectPool>();
static ObjectObjectPool GetPool(Type type)
{
ObjectObjectPool pool;
_pools.TryGetValue(type, out pool);
if (pool == null)
{
pool = new ObjectObjectPool(type);
_pools.Add(type, pool);
}
return pool;
}
public static T Take<T>() where T : class, new()
{
var pool = GetPool(typeof(T));
return (T)pool.Take();
}
public static void Free<T>(T obj) where T : class, new()
{
var pool = GetPool(typeof(T));
pool.Free(obj);
}
}
}