Hello,
I try to create a generic ObjectPool for my game that takes IPoolables and has a function that creates a number of IPoolables when needed. But I am running into trouble since I cannot do:
var obj = new T();
without telling doing ObjectPool<T: Constructible>
but I cannot create an IPoolable that has an init that takes an ObjectPool<T: Constructible> because haxe sais:
parameter must class or enuum.
Is there a package that solves this allready?
here is the code:
interface IPoolable {
public function init(pool: ObjectPool<Constructible>):Void;
}
typedef Constructible = { public function new():Void; };
@:generic
class ObjectPool<T: Constructible> {
public var pool:Array<T> = [];
public var batchSize:Float = 10;
public function new() {
}
public function createMore():Void {
var i:Int = 0;
while (i < this.batchSize) {
var o = new T();
if(Std.is(o, IPoolable)) {
cast(o, IPoolable).init(this);
}
this.pool.push(o);
i++;
}
}
public function get():T {
if (this.pool.length == 0) {
this.createMore();
}
var result:T = this.pool.pop();
if (Std.is(result, IClearable)) {
cast(result, IClearable).clear();
}
return result;
}
public function release(obj:T):Void {
this.pool.push(obj);
}
}