/**
 * Created by rockyl on 2018/8/1.
 *
 * 对象池
 */

let all = {};

function getGroup(name: string) {
	let group = all[name];
	if (!group) {
		throw new Error('group ' + name + ' not registered.');
	}

	return group;
}

/**
 * 注册一个池
 * @param name 池名称
 * @param newFunc 实例化方法
 * @param initFunc 初始化方法
 */
export function register(name: string, newFunc: () => any, initFunc: (instance: any, ...params) => void) {
	all[name] = {name, newFunc, initFunc, pool: []};
}

/**
 * 获取一个对象
 * @param name 池名称
 * @param params 参数
 */
export function get(name: string, ...params) {
	let group = getGroup(name);

	let {newFunc, initFunc, pool} = group;

	let instance;
	if (pool.length == 0) {
		instance = newFunc();
	} else {
		instance = pool.pop();
	}

	initFunc(instance, ...params);

	return instance;
}

/**
 * 回收一个对象
 * @param name 池名称
 * @param instance 实例
 */
export function recycle(name: string, instance) {
	let group = getGroup(name);

	group.pool.push(instance);
}