当前位置: 移动技术网 > IT编程>开发语言>c# > Unity通用泛型单例设计模式(普通型和继承自MonoBehaviour)

Unity通用泛型单例设计模式(普通型和继承自MonoBehaviour)

2020年08月17日  | 移动技术网IT编程  | 我要评论
单例模式是设计模式中最为常见的,不多解释了。但应该尽量避免使用,一般全局管理类才使用单例。普通泛型单例:public abstract class singleton<t> where t

单例模式是设计模式中最为常见的,不多解释了。但应该尽量避免使用,一般全局管理类才使用单例。

普通泛型单例:

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

继承monobehaviour的泛型单例:

using unityengine;

public abstract class monosingleton <t>: monobehaviour where t:monobehaviour
{
  private static t instance = null;

  private static readonly object locker = new object();

  private static bool bappquitting;

  public static t instance
  {
    get
    {
      if (bappquitting)
      {
        instance = null;
        return instance;
      }

      lock (locker)
      {
        if (instance == null)
        {
          instance = findobjectoftype<t>();
          if (findobjectsoftype<t>().length > 1)
          {
            debug.logerror("不应该存在多个单例!");
            return instance;
          }

          if (instance == null)
          {
            var singleton = new gameobject();
            instance = singleton.addcomponent<t>();
            singleton.name = "(singleton)" + typeof(t);
            singleton.hideflags = hideflags.none;
            dontdestroyonload(singleton);
          }
          else
            dontdestroyonload(instance.gameobject);
        }
        instance.hideflags = hideflags.none;
        return instance;
      }
    }
  }

  private void awake()
  {
    bappquitting = false;
  }

  private void ondestroy()
  {
    bappquitting = true;
  }
}

使用方法直接用类去继承这两个抽象单例即可,使用t.instance就可以直接取得该类(t)的唯一实例了。

以上就是unity通用泛型单例设计模式(普通型和继承自monobehaviour)的详细内容,更多关于unity单例设计模式的资料请关注移动技术网其它相关文章!

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网