/* author: YKMoon * 单例模式基类,可以直接继承 * 继承ISingletonEventHandler接口可以接收事件 */ using UnityEngine; using System.Collections; namespace YKMoon { /// /// 单例初始化接口,想在单例创建时调用自定义初始化函数时继承 /// public interface IUSingletonEventHandler { /// /// 创建单例时调用,主要用于像mono这种不能在构造函数写东西的 /// void OnCreateSingleton(); } /// /// 单例类 /// 使用例子: /// public class A: USingleton<A> /// /// public class USingleton where T : new() { private static T _instance; public static T Instance { get { if(_instance == null) { _instance = new T(); if(_instance is IUSingletonEventHandler) { (_instance as IUSingletonEventHandler).OnCreateSingleton(); } } return _instance; } } } /// /// 单例类,继承自YKMono,有MonoBehaviour特性会产生GameObject /// 使用例子: /// public class A: USingletonMono<A> /// /// public class USingletonMono : YKMono where T : YKMono { private static T _instance; public static T Instance { get { if(_instance == null) { GameObject obj = new GameObject(typeof(T).Name); GameObject.DontDestroyOnLoad(obj); _instance = obj.AddComponent(); if(_instance is IUSingletonEventHandler) { (_instance as IUSingletonEventHandler).OnCreateSingleton(); } } return _instance; } } } public class USingletonHidingMono : YKMono where T: YKMono { private static T _instance; public static T Instance { get { if(_instance == null) { GameObject obj = new GameObject(typeof(T).Name); GameObject.DontDestroyOnLoad(obj); obj.hideFlags |= HideFlags.HideInHierarchy; _instance = obj.AddComponent(); if(_instance is IUSingletonEventHandler) { (_instance as IUSingletonEventHandler).OnCreateSingleton(); } } return _instance; } } } /// /// 单例类,继承自YKMono,自定义注册型,会在Awake时注册到Instance. /// 使用时要注意为null的情况. /// public class USingletonMonoCustom : YKMono where T : YKMono { private static T _instance; public static T Instance { get { if(_instance == null) { throw new System.NullReferenceException("Singleton is not regist.Call Instance after mono Awake."); } return _instance; } } protected override void Awake() { _instance = gameObject.GetComponent(); GameObject.DontDestroyOnLoad(gameObject); if(_instance is IUSingletonEventHandler) { (_instance as IUSingletonEventHandler).OnCreateSingleton(); } base.Awake(); } } /// /// 单例类,线程安全型 /// public class UTFSingleton where T : new() { private static T _instance = default(T); private static readonly object padlock = new object(); public static T Instance { get { lock(padlock) { if(_instance == null) { _instance = new T(); if(_instance is IUSingletonEventHandler) { (_instance as IUSingletonEventHandler).OnCreateSingleton(); } } return _instance; } } } } }