上一篇:Unity客户端开发(初级)面试总结-- C# 基础
提到了静态构造函数与静态字段的一些性质,可以很好的用来实现懒加载(懒汉)的单例模式。
单例模式
public class Singleton<T> where T : class, new()
{
private Singleton()
{
}
private class InnerSingleton
{
internal static readonly T Instance = new T();
static InnerSingleton()
{
}
}
public static T Instance { get { return InnerSingleton.Instance; } }
}
- 线程安全:CLR保证静态字段赋值在每个AppDomain中只执行一次;
- 懒加载:使用静态构造函数抑制了JIT编译器的
beforefieldinit
调用模式,从而通过precise
模式调用(详见下面参考)。
参考:
[C#]BeforeFieldInit 与类静态构造函数
C# 静态内部类单例模式-静态变量何时初始化
Mono单例模式
public class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static bool _destroyed = false;
private static T _instance;
private static readonly object _lock = new object(); // 加锁
public static T Instance
{
get
{
if (_destroyed) return null;
if (_instance == null)
{
lock (_lock)
{
if (_instance == null)
{
T[] instances = FindObjectsOfType<T>();
int insCount = instances.Length;
if (insCount == 1)
{
_instance = instances[0];
}
else if (insCount > 1)
{
for (int i = 1; i < insCount; i++) // 只留一个,保证唯一性
{
DestroyImmediate(instances[i]);
}
_instance = instances[0];
}
else
{
GameObject singleton = new GameObject("Singleton of" + typeof(T));
DontDestroyOnLoad(singleton);
_instance = singleton.AddComponent<T>();
}
}
}
}
return _instance;
}
}
protected virtual void OnDestroy()
{
_destroyed = true;
}
}
参考:
Unity中Mono脚本单例模式
Unity 游戏框架搭建 2017 (三) MonoBehaviour 单例的模板