Advertisement
fcamuso

Singleton - 3

Jan 18th, 2021
532
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.50 KB | None | 0 0
  1. using System;
  2.  
  3. namespace SingletonFull
  4. {
  5.  
  6.   //class MyClass
  7.   //{
  8.   //  static private readonly Lazy<int> valore = new Lazy<int>(() => Sum(1, 2));
  9.   //  static public int Valore => valore.Value;
  10.   //  static public int Sum(int a, int b)
  11.   //  {
  12.   //    Console.WriteLine($"Esecuzione Sum {a} - {b}");
  13.   //    return a + b;
  14.   //  }
  15.  
  16.   //  static MyClass() { Console.WriteLine("costruttore statico"); }
  17.  
  18.   //}
  19.  
  20.  
  21.   class MyClassNoLazy
  22.   {
  23.     static public readonly MyClassNoLazy Instance = new MyClassNoLazy();
  24.     //public static int valore = 0; //forza inizializzazione eager di Instance
  25.     private MyClassNoLazy() { Console.WriteLine("costruttore"); }
  26.     static MyClassNoLazy() { }
  27.   }
  28.  
  29.   class MyClassLazy
  30.   {
  31.     static private readonly Lazy<MyClassLazy> instance = new Lazy<MyClassLazy>(() => new MyClassLazy());
  32.     static public MyClassLazy Instance => instance.Value;
  33.  
  34.     public static int valore = 0;
  35.     private MyClassLazy() { Console.WriteLine("costruttore"); }
  36.   }
  37.  
  38.   //Credits: Jon Skeet https://csharpindepth.com/Articles/Singleton#nested-cctor
  39.   public sealed class Singleton
  40.   {
  41.     public static int valore = 0;
  42.     private Singleton() { Console.WriteLine("costruttore"); }
  43.  
  44.     public static Singleton Instance => Nested.instance;
  45.  
  46.     private class Nested
  47.     {
  48.       internal static readonly Singleton instance = new Singleton();
  49.     }
  50.   }
  51.  
  52.  
  53.   class Program
  54.   {
  55.     static void Main(string[] args)
  56.     {
  57.       int d = Singleton.valore;
  58.     }
  59.   }
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement