Files
esengine/source/src/Utils/Collections/Pool.ts

79 lines
2.3 KiB
TypeScript
Raw Normal View History

2020-08-28 19:12:21 +08:00
module es {
/**
*
*/
export class Pool {
private static _objectQueue: Map<any, any[]> = new Map();
2020-08-28 19:12:21 +08:00
/**
* 使cacheCount对象填充缓存
* @param type
* @param cacheCount
*/
public static warmCache<T>(type: new (...args) => T, cacheCount: number) {
this.checkCreate(type);
cacheCount -= this._objectQueue.get(type).length;
2020-08-28 19:12:21 +08:00
if (cacheCount > 0) {
for (let i = 0; i < cacheCount; i++) {
2022-03-07 22:52:51 +08:00
this._objectQueue.get(type).push(new type());
2020-08-28 19:12:21 +08:00
}
}
}
/**
* cacheCount项目
* @param cacheCount
*/
public static trimCache<T>(type: new (...args) => T, cacheCount: number) {
this.checkCreate(type);
while (cacheCount > this._objectQueue.get(type).length)
2022-03-07 22:52:51 +08:00
this._objectQueue.get(type).splice(0, 1);
2020-08-28 19:12:21 +08:00
}
/**
*
*/
public static clearCache<T>(type: new (...args) => T) {
this.checkCreate(type);
this._objectQueue.get(type).length = 0;
2020-08-28 19:12:21 +08:00
}
/**
*
*/
public static obtain<T>(type: new (...args) => T): T {
this.checkCreate(type);
if (this._objectQueue.get(type).length > 0)
return this._objectQueue.get(type).shift();
2020-08-28 19:12:21 +08:00
return new type() as T;
}
/**
*
* @param obj
*/
public static free<T>(type: new (...args) => T, obj: T) {
this.checkCreate(type);
2022-03-07 22:52:51 +08:00
this._objectQueue.get(type).push(obj);
2020-08-28 19:12:21 +08:00
if (isIPoolable(obj)) {
2020-08-28 19:12:21 +08:00
obj["reset"]();
}
}
private static checkCreate<T>(type: new (...args) => T) {
2022-03-07 22:52:51 +08:00
if (!this._objectQueue.has(type))
this._objectQueue.set(type, []);
}
2020-08-28 19:12:21 +08:00
}
export interface IPoolable {
/**
*
*/
reset();
}
export var isIPoolable = (props: any): props is IPoolable => typeof (props as IPoolable)['reset'] !== 'undefined';
2020-08-28 19:12:21 +08:00
}