BattleDataPool.ts 1018 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // 战斗数据节点池
  2. export class BattleDataPool<T> {
  3. private pool: T[] = [];
  4. private creator: new () => T;
  5. private maxSize: number;
  6. constructor(creator: new()=>T,maxSize: number) {
  7. if(this.creator == null){
  8. this.creator = creator
  9. }
  10. this.maxSize = maxSize;
  11. }
  12. // 从池中获取对象
  13. public getObject(): T | null {
  14. if (this.pool.length > 0) {
  15. return this.pool.pop()!;
  16. } else if (this.pool.length < this.maxSize) {
  17. return new this.creator();
  18. }
  19. return null; // 池已满且没有可用对象
  20. }
  21. // 将对象放回池中
  22. public putObject(obj: T): void {
  23. if (this.pool.length < this.maxSize) {
  24. this.pool.push(obj);
  25. }
  26. }
  27. /**
  28. * 设置节点池大小
  29. * @param size 大小
  30. */
  31. setPoolSize(size: number) {
  32. this.maxSize = size;
  33. }
  34. /**
  35. * 清理节点池
  36. */
  37. clear() {
  38. this.pool = [];
  39. }
  40. }