From ec91398d7f2ab9db88019a1837a4b7b1aedd7d0a Mon Sep 17 00:00:00 2001 From: Pedro Avila Date: Mon, 2 Oct 2023 19:28:57 -0500 Subject: [PATCH] Implemetacion de Singleton --- Starter solution/Singleton/Implementation.cs | 31 ++++++++++++++++++++ Starter solution/Singleton/Program.cs | 17 ++++++++++- 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/Starter solution/Singleton/Implementation.cs b/Starter solution/Singleton/Implementation.cs index ba01372..3326e38 100644 --- a/Starter solution/Singleton/Implementation.cs +++ b/Starter solution/Singleton/Implementation.cs @@ -1,4 +1,35 @@ namespace Singleton { + + public class Logger + { + // Lazy + private static readonly Lazy _lazyLogger + = new Lazy(() => new Logger()); + + //private static Logger? _instance; + + public static Logger Instance + { + get + { + return _lazyLogger.Value; + //if (_instance == null) + // _instance = new Logger(); + //return _instance; + } + } + + protected Logger() + { + } + + /// + /// SingletonOperation + /// + /// + public void Log(string message) => Console.WriteLine($"Message to log: {message}"); + + } } diff --git a/Starter solution/Singleton/Program.cs b/Starter solution/Singleton/Program.cs index 1dfa0be..c6f72e6 100644 --- a/Starter solution/Singleton/Program.cs +++ b/Starter solution/Singleton/Program.cs @@ -1 +1,16 @@ -Console.Title = "Singleton"; \ No newline at end of file +using Singleton; + +Console.Title = "Singleton"; + +var instance1 = Logger.Instance; +var instance2 = Logger.Instance; + +if (instance1 == instance2 && instance2 == Logger.Instance) + Console.WriteLine("Instances are the same."); + +instance1.Log($"Message from {nameof(instance1)}"); +instance1.Log($"Message from {nameof(instance2)}"); + +Logger.Instance.Log($"Message from {nameof(Logger.Instance)}"); + +Console.ReadLine();