diff --git a/Blarg.GameFramework/Blarg.GameFramework.csproj b/Blarg.GameFramework/Blarg.GameFramework.csproj index a8d4abe..de74197 100644 --- a/Blarg.GameFramework/Blarg.GameFramework.csproj +++ b/Blarg.GameFramework/Blarg.GameFramework.csproj @@ -140,6 +140,7 @@ + diff --git a/Blarg.GameFramework/Support/ObjectPools.cs b/Blarg.GameFramework/Support/ObjectPools.cs new file mode 100644 index 0000000..e84b859 --- /dev/null +++ b/Blarg.GameFramework/Support/ObjectPools.cs @@ -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 + { + Type _type; + + public ObjectObjectPool(Type type) + : base(INITIAL_CAPACITY) + { + _type = type; + } + + protected override object Allocate() + { + return Activator.CreateInstance(_type); + } + } + + static Dictionary _pools = new Dictionary(); + + 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() where T : class, new() + { + var pool = GetPool(typeof(T)); + return (T)pool.Take(); + } + + public static void Free(T obj) where T : class, new() + { + var pool = GetPool(typeof(T)); + pool.Free(obj); + } + } +} +