java 单例模式 泛型_Unity通用泛型单例设计模式(普通型和继承自MonoBehaviour)

单例模式是设计模式中最为常见的,不多解释了。但应该尽量避免使用,一般全局管理类才使用单例。

普通泛型单例:

public abstract class Singleton where T : class, new()

{

private static T instance = null;

private static readonly object locker = new object();

public static T Instance

{

get

{

lock (locker)

{

if (instance == null)

instance = new T();

return instance;

}

}

}

}

继承MonoBehaviour的泛型单例:

using UnityEngine;

public abstract class MonoSingleton : MonoBehaviour where T:MonoBehaviour

{

private static T instance = null;

private static readonly object locker = new object();

private static bool bAppQuitting;

public static T Instance

{

get

{

if (bAppQuitting)

{

instance = null;

return instance;

}

lock (locker)

{

if (instance == null)

{

instance = FindObjectOfType();

if (FindObjectsOfType().Length > 1)

{

Debug.LogError("不应该存在多个单例!");

return instance;

}

if (instance == null)

{

var singleton = new GameObject();

instance = singleton.AddComponent();

singleton.name = "(singleton)" + typeof(T);

singleton.hideFlags = HideFlags.None;

DontDestroyOnLoad(singleton);

}

else

DontDestroyOnLoad(instance.gameObject);

}

instance.hideFlags = HideFlags.None;

return instance;

}

}

}

private void Awake()

{

bAppQuitting = false;

}

private void OnDestroy()

{

bAppQuitting = true;

}

}

使用方法直接用类去继承这两个抽象单例即可,使用T.Instance就可以直接取得该类(T)的唯一实例了。

以上就是Unity通用泛型单例设计模式(普通型和继承自MonoBehaviour)的详细内容,更多关于unity单例设计模式的资料请关注脚本之家其它相关文章!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值