using System.Collections.Generic;
using System.Diagnostics;
namespace TBL.CSharp.Utilities
{
///
/// 对象池
///
public class ObjectPool where T : new()
{
///
/// 对象集合
///
private readonly Queue _set = new Queue();
///
/// 全局对象
///
public static readonly ObjectPool Global = new ObjectPool();
///
/// 剩余对象计数
///
public int RemainCount => _set.Count;
///
/// 回收池对象
///
public void Recycle(T instance)
{
Debug.Assert(instance != null);
_set.Enqueue(instance);
}
///
/// 预分配
///
public void Preallocate(int size)
{
for (var i = 0; i < size; i++)
_set.Enqueue(new T());
}
///
/// 获取一个池对象
/// 注意手动初始化和清理
///
public T Use()
{
return _set.Count > 0
? _set.Dequeue()
: new T();
}
///
/// 清空池对象
///
public void Clear()
{
_set.Clear();
}
}
}