0%

一个通用Typescript对象池

ObjectPool.ts

/**
* 可以加入对象池的对象
*
* @export
* @interface IPoolObject
*/
export interface IPoolObject {
/**
* 重置的方法
*
* @memberof IPoolObject
*/
reset() : void
}

/**
* 对象池
*
* @export
* @class ObjectPool
*/
export class ObjectPool {
private static _instance: ObjectPool
private constructor() {}
static get Inst() : ObjectPool {
if (!ObjectPool._instance) {
ObjectPool._instance = new ObjectPool()
}
return ObjectPool._instance
}
private _poolMap: Map<any, Array<any>> = new Map<any, Array<any>>()

/**
* 释放有对象池
*
* @template T
* @param {{ new(): T}} Class
* @returns {boolean}
* @memberof ObjectPool
*/
hasPool<T extends IPoolObject>(Class: { new(): T}) : boolean {
return !!this._poolMap.get(Class)
}

/**
* 加入对象池
*
* @template T
* @param {T} obj
* @memberof ObjectPool
*/
put<T extends IPoolObject>(obj: T) : void {
if (!this._poolMap.get(obj)) {
this._poolMap.set(obj, new Array<T>())
}
// 重置对象
obj.reset()
this._poolMap.get(obj.constructor).push(obj)
}

/**
* 取出数据
*
* @template T
* @param {{ new(): T }} Class
* @returns {T}
* @memberof ObjectPool
*/
get<T extends IPoolObject>(Class:{ new(): T }) : T {
if (!this._poolMap.get(Class)) {
this._poolMap.set(Class, new Array<T>())
}
let pool = this._poolMap.get(Class)
if (!pool.length) {
this._factoryCreate(Class, pool)
}
return pool.pop()
}

/**
* 初始化对象池
*
* @template T
* @param {{ new(): T}} Class
* @param {number} [count=10]
* @memberof ObjectPool
*/
initPool<T extends IPoolObject>(Class: { new(): T}, count: number = 10) : void{
if (!this._poolMap.get(Class)) {
this._poolMap.set(Class, new Array<T>())
}
let pool = this._poolMap.get(Class)
if (!pool.length) {
this._factoryCreate(Class, pool, count)
}
}

/**
* 清除所有
*
* @memberof ObjectPool
*/
clearAll() {
// TODO 如果需要释放资源 在这里做
this._poolMap = new Map<any, Array<any>>()
}

/**
* 批量创建对象
*
* @private
* @template T
* @param {{ new(): T}} Class
* @param {number} [count=10]
* @memberof ObjectPool
*/
private _factoryCreate<T> (Class: { new(): T}, pool: Array<T>, count: number = 10) : void {
for (let i = 0; i < count; i++) {
pool.push(new Class())
}
}

}

欢迎关注我的其它发布渠道