45 lines
905 B
C#
45 lines
905 B
C#
using System.Collections.Generic;
|
|
|
|
public class GenericPool<T> where T : new()
|
|
{
|
|
private Queue<T> _pool = new Queue<T>();
|
|
private int _maxSize;
|
|
|
|
public GenericPool(int initialSize, int maxSize)
|
|
{
|
|
_maxSize = maxSize;
|
|
for (int i = 0; i < initialSize; i++)
|
|
{
|
|
_pool.Enqueue(new T());
|
|
}
|
|
}
|
|
|
|
// 从对象池中获取一个对象
|
|
public T Get()
|
|
{
|
|
if (_pool.Count > 0)
|
|
{
|
|
return _pool.Dequeue();
|
|
}
|
|
|
|
// 如果池为空且未达到最大大小,则创建新对象
|
|
if (_pool.Count < _maxSize)
|
|
{
|
|
return new T();
|
|
}
|
|
|
|
// 如果池已满,返回默认值(或抛出异常)
|
|
return default(T);
|
|
}
|
|
|
|
// 将对象回收到对象池中
|
|
public void Return(T item)
|
|
{
|
|
if (item == null) return;
|
|
|
|
if (_pool.Count < _maxSize)
|
|
{
|
|
_pool.Enqueue(item);
|
|
}
|
|
}
|
|
} |