I have an object pool, and I need to call a delegate method OnFree(), whenever I call Free() on an object in the pool.
Free() is created externally and set on the object when the pool is created. OnFree differs from one object to another, and sometimes it is even null.
Objects in the pool inherit from the Poolable class.
class Poolable
{
public Action Free();
public Action OnFree();
}
Currently I create OnFree in the inheriting class by doing this:
class Light
{
public Light()
{
// Create method to be called when Free() is called on this light.
OnFree = () =>
{
DoStuffHere();
};
}
}
However, this will create a separate delegate for each light, which wastes a bunch of memory especially when there are tens of thousands of objects in the pool. Er, it does create a new delegate every time this constructor is called, right?
What is a good way to allow objects to create their own OnFree() delegate, so that there is only one delegate per object type, instead of one delegate per instance?
I can think of a way of course, but I'm hoping someone can think of a "good" way -- something that allows easy maintainability.
Edit: Can I make the OnFree() delegate static in the base class, so that it is static per inherited type somehow?
Edit: To clarify how Pool is used, and why Free()
is a delegate, not a virtual method. Please let me know if you can think of a better way to do this.
public class Pool<T> where T : Poolable
{
private int _liveCount;
private T[] _pool;
[...]
public Pool(int capacity, Func<T> allocateFunction)
{
[...]
// Fill pool with initial items:
for (int i = 0; i < capacity; i++)
{
T item = _allocate();
item.Free = () => Free(item);
_pool[i] = item;
}
}
/// <summary>
/// Frees given object from this pool. Object is assumed to
/// be in this pool.
/// </summary>
public void Free(Poolable obj)
{
obj.OnFree();
_liveCount -= 1;
[...]
}
}