一. 泛型单例
public class Singleton<T> {
private T _instance;
private readonly object _locker = new object();
public T Instance {
get {
if (_instance == null) {
lock (_locker) {
if (_instance == null) {
Type t = typeof(T);
ConstructorInfo[] ctors = t.GetConstructors();
if (ctors.Length > 0) {
throw new InvalidOperationException(String.Format("{0} has at least one accesible ctor", t.Name));
}
_instance = (T)Activator.CreateInstance(t, true);
}
}
}
return _instance;
}
}
}
二. 继承Mono的泛型单例
1. 饿汉式
需在Scene中手动挂载到GameObject上
第一种
public class SingletonMono<T> : MonoBehaviour where T : MonoBehaviour {
private static T _instance;
public static T Instance {
get {
if (_instance == null) {
if (Debug.isDebugBuild) {
Debug.LogError(typeof(T) + " has no instance");
}
}
return _instance;
}
}
private void Awake() {
if (_instance != null) {
if (Debug.isDebugBuild) {
Debug.LogError(typeof(T) + " had has an instance");
}
}
_instance = this as T;
InitAwake();
}
protected virtual void InitAwake() { }
}
使用
public class GameManager : SingletonMono<GameManager> {
protected override void InitAwake() {
}
}
第二种
public class SingletonMono<T> : MonoBehaviour where T : MonoBehaviour {
private static T _instance;
public static T Instance {
get {
if (_instance == null) {
if (Debug.isDebugBuild) {
Debug.LogError(typeof(T) + " has no instance");
}
}
return _instance;
}
}
protected void Awake() {
if (_instance != null) {
if (Debug.isDebugBuild) {
Debug.LogError(typeof(T) + " had has an instance");
}
}
_instance = this as T;
}
}
使用
public class GameManager : SingletonMono<GameManager> {
public new void Awake() {
base.Awake();
}
}
2. 懒汉式
使用时创建
public class SingletonMonoAuto<T> : MonoBehaviour where T : MonoBehaviour {
private static T _instance;
private static bool ApplicationIsQuitting;
private static readonly object _locker = new object();
static SingletonMonoAuto() { ApplicationIsQuitting = false; }
void OnApplicationQuit() {
ApplicationIsQuitting = true;
}
public static T Instance {
get {
if (ApplicationIsQuitting) {
if (Debug.isDebugBuild) Debug.LogError("can't get instance");
}
if (_instance == null) {
lock (_locker) {
if (_instance == null) {
_instance = FindObjectOfType<T>();
if (_instance == null) {
GameObject obj = new GameObject("SingltonMonoAuto_" + typeof(T));
_instance = obj.AddComponent<T>();
}
}
}
}
return _instance;
}
}
}
|