C#中单例模板
泛型单例
/**
* 泛型单例模板
where 限制这个单例类必须要能被new出来
*/
public class Singleton<T> : IDisposable where T : new()
{
private static T instance;
public static T Instance
{
get {
if (instance == null) instance = new T();
return instance;
}
}
public virtual void Dispose()
{
}
}
使用如下
public class RoleMgr:Singleton<RoleMgr>
{
private Dictionary<string,GameObject> m_Role = new Dictionary<string, GameObject> ();
public GameObject LoadPlayer(string name)
{
````````````````
}
public override void Dispose()
{
base.Dispose();
m_Role.Clear ();
}
}
// 其他类中只需要使用如下代码即可调用
RoleMgr.Instance.LoadPlayer("player");