优雅的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

output/writing/Unity游戏框架搭建

猜你喜欢

转载自blog.csdn.net/u010125551/article/details/78474724
今日推荐