Created
June 14, 2015 12:23
-
-
Save sonygod/760f2ad60f88ef7ece5c to your computer and use it in GitHub Desktop.
Singleton<T>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace com.qingyi | |
{ | |
public class Singleton<T> | |
where T : class, new() | |
{ | |
private static T mUniqueInstance; | |
public static bool Exists | |
{ | |
get | |
{ | |
return Singleton<T>.mUniqueInstance != null; | |
} | |
} | |
public static T Instance | |
{ | |
get | |
{ | |
if (Singleton<T>.mUniqueInstance == null) | |
{ | |
Singleton<T>.mUniqueInstance = Activator.CreateInstance<T>(); | |
} | |
return Singleton<T>.mUniqueInstance; | |
} | |
set | |
{ | |
Singleton<T>.mUniqueInstance = value; | |
} | |
} | |
static Singleton() | |
{ | |
} | |
public Singleton() | |
{ | |
if (Singleton<T>.mUniqueInstance != null) | |
{ | |
throw new InvalidOperationException(string.Concat("Singleton [", typeof(T), "] cannot be manually instantiated.")); | |
} | |
} | |
public static T Instances() | |
{ | |
if (Singleton<T>.mUniqueInstance == null) | |
{ | |
Singleton<T>.mUniqueInstance = Activator.CreateInstance<T>(); | |
if (Singleton<T>.mUniqueInstance == null) | |
{ | |
} | |
} | |
return Singleton<T>.mUniqueInstance; | |
} | |
public static void Release() | |
{ | |
if (Singleton<T>.Instance != null) | |
{ | |
Singleton<T>.Instance = default(T); | |
} | |
} | |
} | |
public class SingletonMonoBehaviour<T> : MonoBehaviour | |
where T : SingletonMonoBehaviour<T> | |
{ | |
private static SingletonMonoBehaviour<T> uniqueInstance; | |
public static bool Exists | |
{ | |
get; | |
private set; | |
} | |
public static T Instance | |
{ | |
get | |
{ | |
return (T)SingletonMonoBehaviour<T>.uniqueInstance; | |
} | |
} | |
public SingletonMonoBehaviour() | |
{ | |
} | |
protected virtual void Awake() | |
{ | |
if (SingletonMonoBehaviour<T>.uniqueInstance == null) | |
{ | |
SingletonMonoBehaviour<T>.uniqueInstance = this; | |
SingletonMonoBehaviour<T>.Exists = true; | |
} | |
else if (SingletonMonoBehaviour<T>.uniqueInstance != this) | |
{ | |
throw new InvalidOperationException(string.Concat("Cannot have two instances of a SingletonMonoBehaviour : ", typeof(T).ToString(), ".")); | |
} | |
} | |
protected virtual void OnDestroy() | |
{ | |
if (SingletonMonoBehaviour<T>.uniqueInstance == this) | |
{ | |
SingletonMonoBehaviour<T>.Exists = false; | |
SingletonMonoBehaviour<T>.uniqueInstance = null; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment