AudioCore0.1
This commit is contained in:
45
Assets/04.AudioCore/RunTime/GenericPool.cs
Normal file
45
Assets/04.AudioCore/RunTime/GenericPool.cs
Normal file
@@ -0,0 +1,45 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user