
单例是开发中经常用到的模式(特别是小游戏···),合理的使用单例会使开发更加高效便捷,但过多的使用单例易提高耦合,若非必要应该尽量避免。
如下代码,也可以保证一个类只存在一个实例(多余一个需要手动修改),但不需要做成单例:
public class NotSingleton
{
//保证当前场景最多只存在一个实例,但不需要做成单例
static bool isInstance;
//构造函数
public NotSingleton()
{
if (isInstance)
{
//如果此类已经创建过,暂停检查代码
Debug.LogError(this.GetType() + " Is Already Created");
Debug.Break();
}
isInstance = true;
}
//析构函数
~NotSingleton()
{
isInstance = false;
}
}
另外使用单例模板,将会使代码更加简洁:
//继承Mono的单例
public class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T instance;
public static T Instance
{
get
{
if (instance == null)
{
//FindObjectOfType只能查找已被激活的物体
//Resources.FindObjectsOfTypeAll可以查找未被激活的物体
//instance= FindObjectOfType(typeof(T)) as T;
var finds = Resources.FindObjectsOfTypeAll(typeof(T)) as T[];
if (finds.Length > 0)
instance= finds[0];
if (instance == null)
{
GameObject newObj = new GameObject(typeof(T).ToString());
instance = newObj.AddComponent<T>();
}
}
return instance;
}
}
}
//C#的单例
public class CSSingleton<T> where T : class, new()
{
private static T instance;
private static readonly object syslock = new object();
public static T Instance
{
get
{
if (instance == null)
{
lock (syslock)
{
if (instance == null)
{
instance = new T();
}
}
}
return instance;
}
}
}
//使用示例
public class SingletonDemo : Singleton<SingletonDemo>
{
}
本文来自博客园,作者:萧然CS,转载请注明原文链接:https://www.cnblogs.com/z-c-s/p/15112962.html
浙公网安备 33010602011771号