/// <summary>
/// 单例模式基类 主要目的是避免代码的冗余 方便我们实现单例模式的类
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class BaseManager<T> where T:class//,new()
{
private static T instance;
//属性的方式
public static T Instance
{
get
{
if (instance == null)
{
//instance = new T();
//利用反射得到无参私有的构造函数 来用于对象的实例化
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;
}
}
单例模式------不继承Mono
于 2022-01-17 15:22:47 首次发布
本文介绍了一种通用的单例模式基类实现方法,通过泛型和反射技术避免代码冗余,支持任何可通过无参构造函数实例化的类型。文中详细展示了如何使用属性和静态成员确保单例对象的唯一性和延迟加载。
4818

被折叠的 条评论
为什么被折叠?



