普通的泛型单利
//实现普通的单利模式
//where 限制模版的类型,new()指的是这个类型必须要能被实例化
public class Singleton<T> where T:class,new ()
{
private static T _ins;
private static object mutex=new object();
public static T Ins
{
get
{
if(_ins==null)
{
lock(mutex)//保证我们单利,是线程安全的
{
if(_ins==null)
{
_ins= new T();
}
}
}
return ins;
}
}
}
继承了MonoBehaviour的泛型单利
//MonoBehaviour :声音,网络
//Unity单利
public class UnitySingletn<T> :MonoBehaviour where T:Component
{
private static T _ins;
public static T Ins
{
get
{
if(_ins==null)
{
_ins= FindObjectOfType(typeof(T)) as T;
if(_ins==null)
{
GameObject obj = new GameObject();
obj.hideFlags= HideFlags.HideAndDontSave;
_ins=(T)obj.AddComponent(typeof(T));
}
}
return _ins;
}
}
}