QFramework框架学习(一) ------ 单例模式

QFramework 是一套 渐进式 的 快速开发 框架。目标是作为无框架经验的公司、独立开发者、以及 Unity3D 初学者们的 第一套框架。框架内部积累了多个项目的在各个技术方向的解决方案。学习成本低,接入成本低,重构成本低,二次开发成本低,文档内容丰富(提供使用方式以及原理、开发文档)。github:https://github.com/liangxiegame/QFramework


1.无生命周期单例模式

    框架官方介绍 : http://liangxiegame.com/post/2/

public abstract class Singleton<T> : ISingleton where T : Singleton<T>
	{
		protected static T mInstance;

		static object mLock = new object();

		protected Singleton()
		{
		}

		public static T Instance
		{
			get
			{
				lock (mLock)
				{
					if (mInstance == null)
					{
						mInstance = SingletonCreator.CreateSingleton<T>();
					}
				}

				return mInstance;
			}
		}
        //释放
		public virtual void Dispose()
		{
			mInstance = null;
		}

		public virtual void OnSingletonInit()
		{
		}
	}

2.有生命周期单例模式

 public interface ISingleton
 {        
        void OnSingletonInit();
 }
       using UnityEngine;

	public abstract class MonoSingleton<T> : MonoBehaviour, ISingleton where T : MonoSingleton<T>
	{
		protected static T mInstance = null;

		public static T Instance
		{
			get
			{
				if (mInstance == null)
				{
					mInstance = MonoSingletonCreator.CreateMonoSingleton<T>();
				}

				return mInstance;
			}
		}
        //初始化调用
		public virtual void OnSingletonInit()
		{

		}

		public virtual void Dispose()
		{
			if (MonoSingletonCreator.IsUnitTestMode)
			{
				var curTrans = transform;
				do
				{
					var parent = curTrans.parent;
					DestroyImmediate(curTrans.gameObject);
					curTrans = parent;
				} while (curTrans != null);

				mInstance = null;
			}
			else
			{
				Destroy(gameObject);
			}
		}

		protected virtual void OnDestroy()
		{
			mInstance = null;
		}
	}

因为笔者开始参与框架的维护,也希望各位能多多支持~

我们不只是提供框架,更教你学会搭建框架

猜你喜欢

转载自blog.csdn.net/dengshunhao/article/details/80940346