import { IDisposable } from 'ts-toolset'; /** 实例工厂接口 */ export interface IInstanceFactory extends IDisposable { /** 获取实例 */ getInstance(target: { new(...params: any[]): T }, ...params: any[]): T; /** 获取实例,返回实例和标识(标识实例是否是新建的) */ getInstanceAndSign(target: { new(...params: any[]): T }, ...params: any[]): [T, boolean]; /** 回收所有实例 */ recycle(): void; /** 回收指定实例 */ recycle(instance: T): void; /** 回收指定实例集合 */ recycle(instances: T[]): void; } /** 实例工厂 */ export class InstanceFactory implements IInstanceFactory{ /** 可用复用实例 */ private _spareInstances: T[] = []; /** 已被使用的实例 */ private _workingInstances: T[] = []; private _recycleInstance(instance: T) { let index = this._workingInstances.indexOf(instance); if (index > -1) { instance.dispose(); this._workingInstances.splice(index, 1); this._spareInstances.push(instance); } } private _getInstance(target: { new(...params: any[]): T }, params: any[]): [T, boolean] { let isNew = this._spareInstances.length === 0; const instance = isNew ? new target(...params) : this._spareInstances.pop() as T; this._workingInstances.push(instance); return [instance, isNew]; } getInstance(target: { new(...params: any[]): T }, ...params: any[]) { return this._getInstance(target, params)[0]; } getInstanceAndSign(target: { new(...params: any[]): T }, ...params: any[]) { return this._getInstance(target, params); } recycle(): void; recycle(instances: T): void; recycle(instances: T[]): void; recycle(instances: T | T[] = this._workingInstances) { Array.isArray(instances) ? instances.forEach(ins => this._recycleInstance(ins)) : this._recycleInstance(instances); } /** 释放实例 */ dispose() { this._spareInstances.splice(0, this._spareInstances.length); this._workingInstances.splice(0, this._workingInstances.length); } }