com.alicizax.unity.framework/Runtime/ObjectPool/ObjectBase.cs
2026-04-24 14:33:26 +08:00

125 lines
3.1 KiB
C#

namespace AlicizaX.ObjectPool
{
public abstract class ObjectBase : IMemory
{
private string m_Name;
private object m_Target;
private bool m_Locked;
private float m_LastUseTime;
public string Name => m_Name;
public object Target => m_Target;
public bool Locked
{
get => m_Locked;
set => m_Locked = value;
}
public float LastUseTime
{
get => m_LastUseTime;
internal set => m_LastUseTime = value;
}
public virtual bool CustomCanReleaseFlag => true;
protected void Initialize(object target)
{
Initialize(string.Empty, target, false);
}
protected void Initialize(string name, object target)
{
Initialize(name, target, false);
}
protected void Initialize(string name, object target, bool locked)
{
m_Name = name ?? string.Empty;
m_Target = target;
m_Locked = locked;
m_LastUseTime = 0f;
}
protected internal virtual void OnSpawn() { }
protected internal virtual void OnUnspawn() { }
protected internal abstract void Release(bool isShutdown);
public virtual void Clear()
{
m_Name = null;
m_Target = null;
m_Locked = false;
m_LastUseTime = 0f;
}
}
/// <summary>
/// 泛型对象池基类,消除装箱开销
/// </summary>
public abstract class ObjectBase<T> : IMemory where T : class
{
private string m_Name;
private T m_Target;
private bool m_Locked;
private float m_LastUseTime;
public string Name => m_Name;
public T Target => m_Target;
public bool Locked
{
get => m_Locked;
set => m_Locked = value;
}
public float LastUseTime
{
get => m_LastUseTime;
internal set => m_LastUseTime = value;
}
public virtual bool CustomCanReleaseFlag => true;
protected void Initialize(T target)
{
Initialize(string.Empty, target, false);
}
protected void Initialize(string name, T target)
{
Initialize(name, target, false);
}
protected void Initialize(string name, T target, bool locked)
{
m_Name = name ?? string.Empty;
m_Target = target;
m_Locked = locked;
m_LastUseTime = 0f;
if (target is IPoolableObject poolable)
poolable.OnReuse();
}
protected internal virtual void OnSpawn() { }
protected internal virtual void OnUnspawn()
{
if (m_Target is IPoolableObject poolable)
poolable.OnRecycle();
}
protected internal abstract void Release(bool isShutdown);
public virtual void Clear()
{
m_Name = null;
m_Target = null;
m_Locked = false;
m_LastUseTime = 0f;
}
}
}