Unity 游戏框架搭建 2017 (十四) 优雅的 QSignleton (三) 通过属性器实现 Singleton

接下来介绍,不通过继承的方式实现单例模式。大家都出去嗨了,而我却在家码代码... 代码如下:

  • MonoSingletonProperty.cs

    namespace QFramework.Example
    {
      using UnityEngine;
    
      class Class2SignetonProperty : ISingleton
      {
          public static Class2SignetonProperty Instance
          {
              get { return QSingletonProperty<Class2SignetonProperty>.Instance; }
          }
    
          private Class2SignetonProperty() {}
    
          private static int mIndex = 0;
    
          public void OnSingletonInit()
          {
              mIndex++;
          }
    
          public void Dispose()
          {
              QSingletonProperty<Class2SignetonProperty>.Dispose();
          }
    
          public void Log(string content)
          {
              Debug.Log("Class2SingletonProperty" + mIndex + ":" + content);
          }
      }
    
      public class SingletonProperty : MonoBehaviour
      {
          // Use this for initialization
          void Start () 
          {
              Class2SignetonProperty.Instance.Log("Hello World!");    
    
              // delete current instance
              Class2SignetonProperty.Instance.Dispose();
    
              // new instance
              Class2SignetonProperty.Instance.Log("Hello World!");
          }
      }
    }
    

```

  • 必须要实现 OnSingletonInit()、和 Dispose() 方法。
  • 使用这种方式的好处有很多,导出给 Lua 的时候只需简单封装一个 Wrapper 就可以用了,而不用每个父类都进行导出 Lua。而且有的 Lua 插件对泛型支持的不是很好。

结果:


转载请注明地址:凉鞋的笔记:liangxiegame.com

更多内容

原文地址:https://www.cnblogs.com/liangxiegame/p/you-ya-deQSignleton-san-tong-guo-shu-xing-qi-shi-x.html