一、单例模式
它写起来简单,使用起来也是爽的飞起,可以全局访问,想点哪里点哪里。
保证一个类仅有一个实例,并且有生命周期
提供一个全局访问点,在任何地方都可以获取
单一例子实例化
以上基本上就是它的作用了,作者是 Unity3D游戏开发的童鞋,使用到的框架中全场只有一个大单例,不会说出现空指针的情况,但是如果使用多单例的话很容易出现一个获取的先后问题而报错。 但是这里博主还是将单例模板进行列举出来。。

Mono单例

//==========================
// - FileName: MonoSingleton.cs
// - Created: true.
// - CreateTime: 2020/02/28 22:24:15
//
// - Region: China WUHAN
// - Description:
//==========================
using UnityEngine;

public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance = null;
public static T Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<T>();
if (_instance == null)
{
Debug.LogError("Scene Dont NullObject" + typeof(T).Name);
}
}
return _instance;
}
}

private void Awake()
{
//if (_instance == null)
//{
// DontDestroyOnLoad(gameObject);
//}
//else
//{
// Destroy(gameObject);
//}

_instance = this as T;

}
}

普通单例:

//==========================
// - FileName: SingletonNormal.cs
// - Created: true.
// - CreateTime: 2020/10/19 23:23:11

// - Region: China WUHAN
// - Description: 普通单例类
//==========================
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NormalSingleton<T> where T : class,new ()
{
private static T _instance;
public static T Instance
{
get
{
if (_instance == null)
{
T t = new T();
if (t is MonoBehaviour)
{
Debug.LogError("Normal Singleton Not Instance MonoSingleton");
}
_instance = t;
}
return _instance;
}
}
}