设计模式之单例模式(Singleton)
发表于2018-11-03

单例是开发中经常用到的模式(特别是小游戏···),合理的使用单例会使开发更加高效便捷,但过多的使用单例易提高耦合,若非必要应该尽量避免。
如下代码,也可以保证一个类只存在一个实例(多余一个需要手动修改),但不需要做成单例:
public class NotSingleton
{
//保证当前场景最多只存在一个实例,但不需要做成单例
static bool isInstance;
//构造函数
public NotSingleton()
{
if (isInstance)
{
//如果此类已经创建过,暂停检查代码
Debug.LogError(this.GetType() + " Is Already Created");
Debug.Break();
}
isInstance = true;
}
//析构函数
~NotSingleton()
{
isInstance = false;
}
}
另外使用单例模板,将会使代码更加简洁:
public abstract class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
//单例
private static T instance;
public static T Instance
{
get
{
if (instance == null)
{
instance = FindObjectOfType(typeof(T)) as T;
if (instance == null)
{
GameObject newObj = new GameObject(typeof(T).ToString());
instance = newObj.AddComponent<T>();
}
}
return instance;
}
}
}
//使用示例
public class SingletonDemo : Singleton<SingletonDemo>
{
}
