单例模式

2020-01-02  本文已影响0人  APP4x

1.如果是普通单例模式
私有构造函数的条件

public class Singleton<T> where T : class
{
    private static T instance;
    public static T Instance
    {
        get
        {
            if (instance == null)
            {
                var ctors = typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic);
                var ctor = Array.Find(ctors, c => c.GetParameters().Length == 0);
                if (ctor == null)
                {
                    Debug.LogError("Non-Public Constructor() not found! in " + typeof(T));
                }
                instance = ctor.Invoke(null) as T;
            }
            return instance;
        }
    }
}

2.如果是继承Monobehaviour的单例

public abstract class MonoSingleton<T> : MonoBehaviour
    where T : MonoSingleton<T>
{
    private static T instance = null;
    public static T Instance
    {
        get
        {
            if (instance == null)
            {
                T[] arr = FindObjectsOfType<T>();

                if (arr.Length > 1)
                {
                    Debug.LogError("Singleton is not only! in " + typeof(T));
                }
                else if (arr.Length == 1)
                {
                    instance = arr[0];
                }
                else
                {
                    string instanceName = typeof(T).Name;
                    GameObject instanceGo = new GameObject(instanceName);
                    instance = instanceGo.AddComponent<T>();
                }
            }
            return instance;
        }
    }

    protected virtual void OnDestroy()
    {
        instance = null;
    }

}
上一篇 下一篇

猜你喜欢

热点阅读