the definition of the singleton pattern: the singleton pattern ensures a class has only one instance, and provides a global point of access to it. that means that only one instance can and will exist with regards to a singleton class.
We can see from our class diagram that our singleton has a static field representing itself, a private constructor to prevent anyone from instantiating it and a static "GetInstance()" method that returns the static instance of our singleton.
using System;
namespace pav.singletonPattern
{
class Singleton
{
static Singleton instance = new Singleton();
private Singleton() { }
public static
Singleton GetInstance() => instance;
public string SayHi()
=> "hi";
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Singleton.GetInstance().SayHi());
}
}
}
using System;
namespace pav.singletonPattern
{
class Singleton
{
static Singleton instance;
private Singleton() {}
public static
Singleton GetInstance() => instance = instance ?? new Singleton();
public string SayHi()
=> "hi";
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Singleton.GetInstance().SayHi());
}
}
}
there is added complexity that is not covered here if you need to asynchronously do a lazy load, but that's a longer story for another day.