一. 泛型单例
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);//true匹配所有无参构造,false仅匹配公有无参构造
}
}
}
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,发布版本不Debug,降低性能影响
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() { }//子类重写该方法当作Awake
}
使用
public class GameManager : SingletonMono<GameManager> {
protected override void InitAwake() {
//DO STH
}
}
第二种
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();
//DO STH
}
}
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;
}
}
}
本文介绍了两种泛型单例设计模式的实现方法:一种是纯泛型单例,另一种是基于Unity框架的MonoBehaviour组件的泛型单例。文中详细展示了饿汉式和懒汉式的具体代码实现,并提供了具体的使用示例。

2375

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



