通用单例类
Posted z-59-46
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了通用单例类相关的知识,希望对你有一定的参考价值。
普通单例类设计:
public abstract class Singleton<T> where T : new() private static T _instance; private static object _lock = new object(); public static T instance get if (_instance == null) object lockObject = Singleton<T>._lock; Monitor.Enter(lockObject); try if (_instance == null) _instance = Activator.CreateInstance<T>(); finally Monitor.Exit(lockObject); return _instance; //public virtual void Init() // //
MomoBehavior类的设计:
public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T> private static T instance = null; private static object lockObject = new object(); public static T Instance get if (instance == null) object obj = MonoSingleton<T>.lockObject; Monitor.Enter(obj); instance = GameObject.FindObjectOfType(typeof(T)) as T; if (instance == null) instance = new GameObject(typeof(T).Name, typeof(T)).GetComponent<T>(); Monitor.Exit(obj); return instance; public virtual void SetDontDestroyOnLoad(Transform parent) transform.parent = parent;
以上是关于通用单例类的主要内容,如果未能解决你的问题,请参考以下文章