How to create an ObjectPool [SOLVED]

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? :slight_smile:

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);
	}

}

I might have solved it. Haven’t actually tried it but it compiles so … how wrong could it be :wink:

interface IPoolable {
	public function init(pool: ObjectPool<IPoolable>):Void;
}

@:generic
class ObjectPool<T: IPoolable> {

	private var pool:Array<T> = [];

	public var batchSize:Int = 10;
	private var _poolType:Class<T>; 

	public function new(_pooledType: Class<T>) {
		this._poolType = _pooledType;
	}

	public function createMore():Void {
		var i:Int;
		for (i in 0...this.batchSize) {
			var o = Type.createInstance(this._poolType, []);
			o.init(cast(this, ObjectPool<IPoolable>));
			this.pool.push(o);
		}
	}

	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);
	}

}

An option is by implementing a linked list, but I think that Array is actually a linked list anyway

Array is an array, not a linked list. On the Flash and AS3 targets, it’s actually a sparse array, but it still isn’t a linked list.

If you want a linked list, use List.