Unity开发通用泛型单例模式

普通的C#单例模式(简单)

public class Singleton<T> where T :new()  {
	private static T m_Instance;

	public static T Instance {
		get {
			if (m_Instance == null) {
				m_Instance = new T();
			}
			return m_Instance;
		}
	}
}

普通的C#单例模式(多线程安全机制)

public abstract class Singleton<T> 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;
            }
        }
    }
}

单例模式(继承需要一个非公有的无参构造函数)

/// <summary>
/// 单例
/// 继承需要一个非公有的无参构造函数
/// </summary>
/// <typeparam name="T">类名的泛型</typeparam>
public abstract class Singleton2<T> where T : class
{
    private static T instance = null;

    // 多线程安全机制
    private static readonly object locker = new object();

    public static T Instance
    {
        get
        {
            // 线程锁
            lock (locker)
            {
                if (null == instance)
                {
                    // 反射获取实例
                    var octors = typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic);

                    // 获取无参数的非公共构造函数
                    var octor = Array.Find(octors, c => c.GetParameters().Length == 0);

                    // 没有则提示没有私有的构造函数
                    if (null == octor)
                    {
                        throw new Exception("No NonPublic constructor without 0 parameter");
                    }

                    // 实例化
                    instance = octor.Invoke(null) as T;
                }

                return instance;

            }
        }
    }

    /// <summary>
    /// 构造函数
    /// 避免外界new
    /// </summary>
    protected Singleton2() { }
}

继承MonoBehaviour的单例模式(一)

using UnityEngine;
public class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
{
    private static T _instance;
    public static T Instance
    {
        get
        {
            if (_instance == null)
            {

                _instance = FindObjectOfType<T>();
                //if (FindObjectOfType<T>() > 1)
                //{
                //    return FindObjectOfType<T>;
                //}
                if (_instance == null)
                {
                    _instance = new GameObject(typeof(T).ToString()).AddComponent<T>();
                }
            }
            return _instance;
        }
    }
}

继承MonoBehaviour的单例模式(二)

using UnityEngine;

public class MonoSingleton<T> : MonoBehaviour where T :MonoSingleton<T> {

	protected static T instance;

	public static T Instance
	{
		get { return instance; }
	}

	protected virtual void Awake()
	{
		if (instance == null)
		{
			instance = (T)this;
		}
		else
		{
			Debug.LogError("Get a second instance of this class" + this.GetType());
		}
	}
}

继承MonoBehaviour的单例模式(三),带初始化函数

/// <summary>
/// 单例[继承MonoBehaviour带Awake]
/// </summary>
public class MonoSingleton2<T> : MonoBehaviour where T : MonoSingleton2<T>
{

    private static T _instance;
    public static T Instance
    {
        get
        {
            if (_instance == null)
                Debug.LogError(typeof(T).ToString() + " is NULL.");
            return _instance;
        }
    }

    private void Awake()
    {
        if (_instance != null)
        {
            //one more Initialize
            Debug.LogError(typeof(T).ToString() + " aready have one on" + _instance.gameObject.name);
        }
        _instance = this as T;//or  _instance = (T)this; 
        //call Init
        Init();
    }

    /// <summary>
    /// 需要在awake初始化的请重载Init
    /// </summary>
    protected virtual void Init()
    {
        //optional to override
    }
}

参考博客地址如下
1、https://www.cnblogs.com/koshio0219/p/11203631.html
2、https://www.codetd.com/article/11599698
3、https://blog.csdn.net/u014361280/article/details/103868778

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值