2020-08-28 19:12:21 +08:00
|
|
|
|
module es {
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 用于池任何对象
|
|
|
|
|
|
*/
|
2021-03-31 16:59:21 +08:00
|
|
|
|
export class Pool {
|
2020-11-03 10:10:03 +08:00
|
|
|
|
private static _objectQueue = [];
|
2020-08-28 19:12:21 +08:00
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 预热缓存,使用最大的cacheCount对象填充缓存
|
|
|
|
|
|
* @param type
|
|
|
|
|
|
* @param cacheCount
|
|
|
|
|
|
*/
|
2021-03-31 16:59:21 +08:00
|
|
|
|
public static warmCache<T>(type: new (...args) => T, cacheCount: number) {
|
2020-08-28 19:12:21 +08:00
|
|
|
|
cacheCount -= this._objectQueue.length;
|
|
|
|
|
|
if (cacheCount > 0) {
|
|
|
|
|
|
for (let i = 0; i < cacheCount; i++) {
|
|
|
|
|
|
this._objectQueue.unshift(new type());
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 将缓存修剪为cacheCount项目
|
|
|
|
|
|
* @param cacheCount
|
|
|
|
|
|
*/
|
2021-02-01 11:11:53 +08:00
|
|
|
|
public static trimCache(cacheCount: number) {
|
2020-08-28 19:12:21 +08:00
|
|
|
|
while (cacheCount > this._objectQueue.length)
|
|
|
|
|
|
this._objectQueue.shift();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 清除缓存
|
|
|
|
|
|
*/
|
|
|
|
|
|
public static clearCache() {
|
|
|
|
|
|
this._objectQueue.length = 0;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 如果可以的话,从堆栈中弹出一个项
|
|
|
|
|
|
*/
|
2021-03-31 16:59:21 +08:00
|
|
|
|
public static obtain<T>(type: new (...args) => T): T {
|
2020-08-28 19:12:21 +08:00
|
|
|
|
if (this._objectQueue.length > 0)
|
|
|
|
|
|
return this._objectQueue.shift();
|
|
|
|
|
|
|
|
|
|
|
|
return new type() as T;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 将项推回堆栈
|
|
|
|
|
|
* @param obj
|
|
|
|
|
|
*/
|
|
|
|
|
|
public static free<T>(obj: T) {
|
|
|
|
|
|
this._objectQueue.unshift(obj);
|
|
|
|
|
|
|
2021-02-01 11:11:53 +08:00
|
|
|
|
if (isIPoolable(obj)) {
|
2020-08-28 19:12:21 +08:00
|
|
|
|
obj["reset"]();
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
export interface IPoolable {
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 重置对象以供重用。对象引用应该为空,字段可以设置为默认值
|
|
|
|
|
|
*/
|
|
|
|
|
|
reset();
|
|
|
|
|
|
}
|
2020-11-23 16:05:06 +08:00
|
|
|
|
|
2020-11-24 12:15:20 +08:00
|
|
|
|
export var isIPoolable = (props: any): props is IPoolable => typeof (props as IPoolable)['reset'] !== 'undefined';
|
2020-08-28 19:12:21 +08:00
|
|
|
|
}
|