Automatically Managed Pools
Monkey Forums/Monkey Code/Automatically Managed Pools
| ||
Pools are often very useful but there are lots of things you have to keep in mind when using them. For example initializing objects when allocating, cleaning things up before freeing objects, freeing the objects into the right pools (you can for example free an object of class B into a Pool<A> if class B extends class A) and so on. The following code should make things a little simpler: Class FObject Field __factory:IFreeFObject Method OnCreate:Void() End Method OnFree:Void() End Method Free:Void() Final OnFree() __factory.IFreeFObject(Self) End End Interface IFreeFObject Method IFreeFObject:Void(o:FObject) End Class Factory<T> Implements IFreeFObject Global __pool := New Pool<T> Global __factory:Factory<T> Function Create:T() Local e:T = __pool.Allocate() e.__factory = __GetFactoryInstance() e.OnCreate() Return e End Function __GetFactoryInstance:Factory<T>() If __factory = Null Then __factory = New Factory<T> Return __factory End Method IFreeFObject:Void(o:FObject) Local e := T(o) e.__factory = Null __pool.Free(e) End End How to use it: Class Thing Extends FObject Method OnCreate:Void() Print("Init") End Method OnFree:Void() Print("Free") End End ' creating an object: Local x := Factory<Thing>.Create() ' freeing an object: x.Free() Factory<xyz>.Create() returns an object of class xyz (which is automatically managed using a pool) and calls the objects OnCreate() method. MyObject.Free() calls OnFree() and returns the object into the correct pool. Keep in mind that you should also call Super.OnCreate() and Super.OnFree() when extending classes (I don't know if there is a better solution to this). |