using System; using System.Diagnostics; namespace Developpez.Dotnet.ComponentModel { /// /// Implémente un singleton avec intialisation tardive pour le type spécifié. /// /// Type de l'objet pour lequel le singleton est implémenté /// Cette implémentation est "lazy" (l'instance du singleton n'est créée que lors /// de sa première utilisation) et thread-safe. L'implémentation est inspirée de l'article /// Implementing the /// Singleton Pattern in C# de Jon Skeet. public static class Singleton { /// /// Retourne l'instance unique du type T /// public static T Instance { get { return LazyInitializer.InternalInstance; } } private static class LazyInitializer { // Constructeur statique explicite pour dire au compilateur C# de // ne pas marquer le type comme 'beforefieldinit' static LazyInitializer() { Debug.WriteLine(string.Format("Initializing singleton instance of type '{0}'", typeof(T).FullName)); } internal static readonly T InternalInstance = (T)Activator.CreateInstance(typeof(T), true); } } }