110,561
社区成员
发帖
与我相关
我的任务
分享
using System;
namespace TEST
{
public sealed class ObjectPool<T> : IPool<T>
where T : class
{
private readonly Func<T> _creater = null;
private readonly Action<T> _rester = null;
private readonly T[] _objs = null;
private readonly int _capcity;
private int _remainer;
public ObjectPool(int capcity, Func<T> creater = null, Action<T> rester = null)
{
_capcity = _remainer = capcity;
_creater = creater;
_rester = rester;
_objs = new T[capcity];
for (int i = 0; i < capcity; i++)
_objs[i] = creater();
}
public int Capcity { get { return _capcity; } }
public int Remainer { get { return _remainer; } }
public T Fetch()
{
if (_remainer <= 0)
throw new Exception();
lock (_objs)
{
return _objs[--_remainer];
}
}
public void Store(T obj)
{
if (_remainer >= _capcity)
throw new Exception();
if (_rester != null)
_rester(obj);
lock (_objs)
{
_objs[_remainer++] = obj;
}
}
}
}