1. 程式人生 > 其它 >單例模式的實現Singleton和MonoSingleton

單例模式的實現Singleton和MonoSingleton

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 普通單例基類
/// by:zdz
/// date:20220328
/// </summary>
/// <typeparam name="T"></typeparam>
public class Singleton<T> where T : new()
{
    private static T m_instance;
    private static readonly object locker = new object();
    public static T Instance
    {
        get
        {
            lock (locker)
            {
                if (m_instance == null) m_instance = new T();
            }
            return m_instance;
        }
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Mono單例基類
/// by:zdz
/// date:20220328
/// </summary>
/// <typeparam name="T"></typeparam>
public class MonoSingleton<T> : MonoBehaviour where T:Component
{
    private static T m_instace;
    private static readonly object lockObj=new object();
    public static T Instance
    {
        get 
        {
            lock (lockObj)
            {
                m_instace = FindObjectOfType<T>();
                if (m_instace == null)
                {
                    GameObject obj = new GameObject("TempObj");
                    m_instace = obj.AddComponent<T>();
                } 
            }          
            return m_instace;
        }
    }
}