Singleton
using System; using System.Reflection; namespace tera.commons.utils { public static class Singleton<T> where T : class { /// <summary> /// The singleton instance itself /// </summary> private static volatile T m_Instance; /// <summary> /// The object used to lock the entire singleton repository. /// </summary> private static object m_Lock = new object(); /// <summary> /// Get the singleton instance of type <see cref="T"/>. /// </summary> public static T Instance { get { // Only create a new instance if there is no instance yet // Lock the entire singleton repository and check again for any racing conditions if (m_Instance == null) lock (m_Lock) if (m_Instance == null) { // Try to get the private/protected constructor from type T ConstructorInfo constructorInfo; try { constructorInfo = typeof(T).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[0], null); } // Could not get the private/protected constructor catch (Exception exception) { throw new Exception("DefaultMessage", exception); } // Make sure we have a private/protected constructor and not an internal one if (constructorInfo == null || constructorInfo.IsAssembly) throw new Exception("DefaultMessage"); // Create a new instance by invoking the constructor m_Instance = (T)constructorInfo.Invoke(null); } // The earlier created instance return m_Instance; } } } }
1. | Singleton Pattern Demo |