美文网首页游戏框架征服Unity3dUnity技术分享
优雅的QSignleton (三) 通过属性器实现Singlet

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

作者: 凉鞋的笔记 | 来源:发表于2017-11-07 10:06 被阅读21次

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

代码如下:

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

结果:

image

相关链接

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

微信公众号:liangxiegame

image

output/writing/Unity游戏框架搭建

相关文章

网友评论

    本文标题:优雅的QSignleton (三) 通过属性器实现Singlet

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