Now I understand Singletone, I found several different implementations in the network, but I still don’t understand how they work. Singleton is a pattern that guarantees the presence of only one instance of a class, and in the examples I don’t understand a little how this “guarantee” is implemented. First example
public sealed class MySingleton { static MySingleton myInstance = null; MySingleton() { } public static MySingleton MyInstance { get { if (myInstance = = null) { myIinstance = new MySingleton(); } return myInstance; } private set; } } Second example:
class Singleton { static Singleton obj; public static Singleton Obj { get { return obj; } } public string Data { get; set; } static Singleton() { obj = new Singleton(); } private Singleton() { Data = "I am a singleton"; } } //вызов { static void Main(string[] args) { Singleton s1 = Singleton.Obj; Console.WriteLine(s1.Data); } } Actually, can you explain how these two examples differ from each other, and how do they guarantee the presence of one instance of a class? Or are they both wrong, and is there a simpler and more understandable implementation of the pattern in c #?
public class Data { public static readonly Data Instance = new Data(); private Data() { } }public class Data { public static readonly Data Instance = new Data(); private Data() { } }- Stack