zoukankan      html  css  js  c++  java
  • 单例模式

    单例模式:是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例的特殊类。通过单例模式可以保证系统中一个类只有一个实例。即一个类只有一个对象实例

    Unity中的单例分为两种,一种是继承自MonoBehaviour的一种是不继承的

    继承自Mono的类不能使用New去创建实例  所以继承自mono的单例可以使用以下方式实现

    //1.继承自泛型基类  单例的核心 是创建出一个物体,添加这个组件,并只返回这个组件 从而实现单例

    public class SingleTonBehaviorBase<T> : MonoBehaviour where T : MonoBehaviour
    {
    private static T _instance;
    public static T GetInstance()
    {
    _instance = GameObject.FindObjectOfType<T>();
    if (_instance == null)
    {
    GameObject goObj = new GameObject(typeof(T).ToString());
    _instance = goObj.AddComponent<T>();
    }
    return _instance;
    }
    }

    //2.自己写  可以使用 Awake 赋值

    public class A

    {

      public static A Instance;

      void Awack()

      {

        Instance = this;

      }

    }

    普通类的单例模式 普通类可以使用new关键字去构造实例,所以方式就很多了

    注意: 要记住在要实现单例的类中声明一个私有的无参构造函数 防止外部创建,如果不声明私有构造,外部可以new出别的实例,就失去了单例的意义

    1.泛型单例  继承 

    public class SingleTonBase<T> where T : new()
    {

    private static T _instance;
    public static T GetInstance()
    {
    if (_instance == null)
    _instance = new T();
    return _instance;
    }

    2.属性

    public class A

    {

      private static A _instance;

      public A Instance{

        get

        {

          if(_instance == null)

            _instance = new A();

          return A;

        }

      }

      //私有构造函数,防止外部创建实例

      private A(){

      }

    }

  • 相关阅读:
    无限维
    黎曼流形
    why we need virtual key word
    TOJ 4119 Split Equally
    TOJ 4003 Next Permutation
    TOJ 4002 Palindrome Generator
    TOJ 2749 Absent Substrings
    TOJ 2641 Gene
    TOJ 2861 Octal Fractions
    TOJ 4394 Rebuild Road
  • 原文地址:https://www.cnblogs.com/FingerCaster/p/7591507.html
Copyright © 2011-2022 走看看