OvertakingLegend/Assets/Script/Tool/Singleton/SingletonManager.cs

42 lines
900 B
C#

public class SingletonManager<T> where T : class, new()
{
/// <summary>
/// 私有静态实例
/// </summary>
private static T instance;
/// <summary>
/// 用于同步的对象
/// </summary>
private static readonly object mlock = new object();
/// <summary>
/// 公共静态属性用于访问实例
/// </summary>
public static T Instance
{
get
{
lock (mlock)//使用锁确保线程安全
{
if (instance == null)//如果实例为空,则创建新实例
{
instance = new T();
}
return instance;
}
}
}
/// <summary>
/// 释放单例
/// </summary>
public virtual void ReleaseInstance()
{
if (instance != null)
{
instance = null; // 释放引用
}
}
}