优雅的QSignleton (三) 通过属性器实现Singleton

来源:互联网 发布:mac bash 3.2 编辑:程序博客网 时间:2024/05/16 08:41

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

代码如下:

  • 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插件对泛型支持的不是很好。

结果:

相关链接

  • QSingleton地址
  • QFramework地址

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

微信公众号:liangxiegame

output/writing/Unity游戏框架搭建