单例模式基类
类不继承mono的单例基类
/// <summary>
/// 单例基类
/// </summary>
//泛型解决,给他一个约束要么是这个类本身要么是它的子类
public class SingleBase<T>where T : SingleBase<T>
{
protected SingleBase() { }
//线程锁。当多线程访问时,同一时刻仅允许一个线程访问。
private static object locker=new object();
//volatile关键字修饰字段是当多个线程都对他进行修改时,确保这个字段在任何时刻呈现都是最新的值
private volatile static T _instance;
public static T Instance
{
get
{
//双重保证对象的唯一性
if (_instance == null)
{
lock (locker)
{
if (_instance == null)
{
//使用反射调用无参构造方法创建对象,就是new一个对象的意思
_instance = Activator.CreateInstance(typeof(T), true) as T;
}
}
}
return _instance;
}
}
}
继承单例基类就不用再写了
public class PlayerModel:SingleBase<PlayerModel>
{
private PlayerModel() { }
public int money=1000;
public int diamond = 888;
public void Show()
{
Debug.Log(money);
Debug.Log(diamond);
}
}
PlayerModel.Instance.Show();
类继承mono的单例基类
/// <summary>
/// 继承monobehaviour的单例基类,前面是继承,where后面是泛型约束,要么是本身,要么是继承monobehaviour
/// </summary>