typescript泛型有非常多的应用,但也有其不足,例如泛型T不能用作值对象处理,因此无法通过T来细分类型。我用泛型实现了通用的对象池管理类,用作大家参考,因类型无法细分,只好将整个类作为一个参数来获取池对象或者回收对象。代码参考如下
class PoolManager {
private static _ins: PoolManager = new PoolManager();
public static get ins() {
return this._ins;
}
protected _objs: any[][] = [];
protected _clses: any[] = [];
private constructor() {
}
public fromPool<T>(cls: { new() : T}): T {
let clsIdx = this._clses.indexOf(cls);
let objList: any[];
if(clsIdx < 0) {
clsIdx = this._clses.length;
this._clses.push(cls);
objList = [];
this._objs.push(objList);
} else {
objList = this._clses[clsIdx];
}
if(objList.length > 0) {
return objList.pop();
} else {
return new cls();
}
}
public toPool<T>(cls: { new() : T}, obj: T) {
if(obj instanceof cls) {
let idx = this._clses.indexOf(cls);
if(idx > -1) {
if(this._objs[idx].indexOf(obj) < 0) {
this._objs[idx].push(obj);
}
}
}
}
}