From d4b861dd58e053d429f97cc5a18a25269bbc9ce9 Mon Sep 17 00:00:00 2001 From: gered Date: Thu, 22 Aug 2013 10:39:28 -0400 Subject: [PATCH] add ObjectPools helper to manage multiple pools for different types automatically --- .../Blarg.GameFramework.csproj | 1 + Blarg.GameFramework/Support/ObjectPools.cs | 54 +++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 Blarg.GameFramework/Support/ObjectPools.cs 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); + } + } +} +