add ObjectPools helper to manage multiple pools for different types automatically
This commit is contained in:
parent
4d49304ec4
commit
d4b861dd58
|
@ -140,6 +140,7 @@
|
|||
<Compile Include="Support\ObjectPool.cs" />
|
||||
<Compile Include="Support\IPoolable.cs" />
|
||||
<Compile Include="Support\BasicObjectPool.cs" />
|
||||
<Compile Include="Support\ObjectPools.cs" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\Portable\$(TargetFrameworkVersion)\Microsoft.Portable.CSharp.targets" />
|
||||
<ItemGroup>
|
||||
|
|
54
Blarg.GameFramework/Support/ObjectPools.cs
Normal file
54
Blarg.GameFramework/Support/ObjectPools.cs
Normal 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in a new issue