【Unity Epitome】C#泛型单例模块

SingletonCreator:单例创建

using System.Reflection;
using UnityEngine;

namespace Epitome
{
    /// <summary>
    /// Singleton Creator.
    /// </summary>
    public static class SingletonCreator
    {
        /// <summary>
        /// Build a Singleton.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T CreateSingleton<T>() where T : class, ISingleton
        {
            // 获取私有构造函数
            var ctors = typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic);

            // 获取无参构造函数
            var ctor = Array.Find(ctors, a => a.GetParameters().Length == 0);

            if (ctor == null)
            {
                throw new SingletonException("Non-Public Constructor() not found! in " + typeof(T));
            }

            T value = ctor.Invoke(null) as T;

            value.OnSingletonInit();

            return value;
        }

        /// <summary>
        /// Build a MonoSingleton.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T CreateMonoSingleton<T>() where T : MonoBehaviour
        {
            T value = MonoBehaviour.FindObjectOfType<T>();

            if (MonoBehaviour.FindObjectsOfType<T>().Length > 1)
            {
                throw new SingletonException(typeof(T) + " object more than 1!");
            }

            if (value == null)
            {
                string name = typeof(T).Name;
                GameObject game = GameObject.Find(name);
                if (game == null) game = new GameObject(name);

                value = game.AddComponent<T>();
            }

            return value;
        }
    }
}

Singleton:单例类

namespace Epitome
{
    /// <summary>
    /// Singleton interface.
    /// </summary>
    public interface ISingleton
    {
        /// <summary>
        /// Singleton initialize.
        /// </summary>
        void OnSingletonInit();
    }

    /// <summary>
    /// Singleton base class. Based on the reflection. Thread safety.
    /// </summary>
    public abstract class Singleton<T>: ISingleton where T : Singleton<T>
    {
        /// <summary>
        /// Initializes a new instance of the Epitome.Singleton class.
        /// </summary>
        protected Singleton() { }

        private static T _Instance = null;

        private static readonly object sysLock = new object();

        /// <summary>
        /// Get an instance of the Epitome.Singleton class
        /// </summary>
        public static T Instance
        {
            get
            {
                lock (sysLock)
                {
                    if (_Instance == null)
                    {
                        _Instance = SingletonCreator.CreateSingleton<T>();
                    }
                }

                return _Instance;
            }
        }

        /// <summary>
        /// Singleton initialize.
        /// </summary>
        public virtual void OnSingletonInit() { }
    }
}

MonoSingleton:MonoBehaviour单例类

using UnityEngine;

namespace Epitome
{
    /// <summary>
    /// MonoBehaviour singleton base class. Thread safety.
    /// </summary>
    public class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
    {
        private static T _Instance = null;

        private static readonly object sysLock = new object();

        /// <summary>
        /// Get an instance of the Epitome.MonoSingletond class.
        /// </summary>
        public static T Instance
        {
            get
            {
                lock (sysLock)
                {
                    if (_Instance == null)
                    {
                        _Instance = SingletonCreator.CreateMonoSingleton<T>();
                    }
                }
                return _Instance;
            }
        }

        /// <summary>
        /// Makes the Epitome.MonoSingleton object not be destroyed automatically when loading a new scene.
        /// </summary>
        protected void DontDestroyOnLoad()
        {
            DontDestroyOnLoad(this);
        }

        /// <summary>
        /// This function is called when the Epitome.MonoSingleton object is destroyed.
        /// </summary>
        protected virtual void OnDestroy()
        {
            _Instance = null;
        }
    }
}

SingletonException:单例错误处理类

using System;

namespace Epitome
{
    /// <summary>
    /// Represents an error that occurred during the execution of the singleton.
    /// </summary>
    public class SingletonException : Exception
    {
        /// <summary>
        /// Initializes a new instance of the Epitome.SingletonException class with a specified error message.
        /// </summary>
        /// <param name="message">The message that describes the error.</param>
        public SingletonException(string message) : base(message)
        {

        }
    }
}

Examples:单例使用范例

using System;

public class Examples : Singleton<Examples>
{
	private Examples() { }

	public override void OnSingletonInit() { }
}
using System;

public class Examples : MonoSingleton<Examples>
{
	private void Awake() { }
	private void Start() { }
	private void Update() { }
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JIQIU.YANG

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值