美文网首页
单例模式

单例模式

作者: APP4x | 来源:发表于2020-01-02 22:49 被阅读0次

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;
    }

}

相关文章

  • 【设计模式】单例模式

    单例模式 常用单例模式: 懒汉单例模式: 静态内部类单例模式: Android Application 中使用单例模式:

  • Android设计模式总结

    单例模式:饿汉单例模式://饿汉单例模式 懒汉单例模式: Double CheckLock(DCL)实现单例 Bu...

  • 2018-04-08php实战设计模式

    一、单例模式 单例模式是最经典的设计模式之一,到底什么是单例?单例模式适用场景是什么?单例模式如何设计?php中单...

  • 设计模式之单例模式详解

    设计模式之单例模式详解 单例模式写法大全,也许有你不知道的写法 导航 引言 什么是单例? 单例模式作用 单例模式的...

  • Telegram开源项目之单例模式

    NotificationCenter的单例模式 NotificationCenter的单例模式分析 这种单例模式是...

  • 单例模式Java篇

    单例设计模式- 饿汉式 单例设计模式 - 懒汉式 单例设计模式 - 懒汉式 - 多线程并发 单例设计模式 - 懒汉...

  • IOS单例模式的底层原理

    单例介绍 本文源码下载地址 1.什么是单例 说到单例首先要提到单例模式,因为单例模式是单例存在的目的 单例模式是一...

  • 单例

    iOS单例模式iOS之单例模式初探iOS单例详解

  • 单例模式

    单例模式1 单例模式2

  • java的单例模式

    饿汉单例模式 懒汉单例模式

网友评论

      本文标题:单例模式

      本文链接:https://www.haomeiwen.com/subject/ehjaoctx.html