45 lines
1.3 KiB
C#
45 lines
1.3 KiB
C#
using System;
|
|
using System.Reflection;
|
|
using UnityEngine;
|
|
/// <summary>
|
|
/// 单例基类
|
|
/// </summary>
|
|
/// <typeparam name="T"></typeparam>
|
|
public abstract class BaseManager<T> where T : class
|
|
{
|
|
private static T instance;
|
|
|
|
/// <summary>
|
|
/// 用于线程锁
|
|
/// </summary>
|
|
protected static readonly object lockObj = new object();
|
|
|
|
public static T Instance
|
|
{
|
|
get
|
|
{
|
|
if (instance == null)
|
|
{
|
|
lock (lockObj)
|
|
{
|
|
if (instance == null)
|
|
{
|
|
//直接Activator 创建
|
|
instance = (T)Activator.CreateInstance(typeof(T), true);
|
|
/*
|
|
//通过反射获取 无参私有构造函数 要求单例对象必须有私有构造函数
|
|
Type type = typeof(T);
|
|
ConstructorInfo info = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
|
|
if (info != null)
|
|
instance = info.Invoke(null) as T;
|
|
else
|
|
Debug.LogError("没有得到对应的无参构造函数!");
|
|
*/
|
|
}
|
|
}
|
|
}
|
|
return instance;
|
|
}
|
|
}
|
|
}
|