A Singleton class in OOP allows only one instance of itself to be created. While a conventional class can have any number of instances created. Below is the thread-safe implementation of Singleton class.
using System;
namespace SingletonPattern
{
// thread-safe way.
public sealed class Singleton
{
private static Singleton obj = null;
// mutex lock used for thread-safety.
private static readonly object mutex = new object();
private int var = 0;
private Singleton()
{
}
public static Singleton getObj
{
get
{
lock (mutex)
{
//lazy loading..
if (obj == null)
{
obj = new Singleton();
}
return obj;
}
}
}
public void doSomething()
{
var += 1;
Console.WriteLine($"Current Value: {var}");
}
}
}
Now, when we call the Singleton class object using getObj from anywhere, it’ll return the same instance of obj.
using System;
namespace SingletonPattern
{
class Program
{
static void Main(string[] args)
{
Singleton instance = Singleton.getObj;
instance.doSomething();
instance.doSomething();
}
}
}
Output:
Current Value: 1
Current Value: 2
An example of a Singleton class can be a Database which returns only 1 instance of itself from wherever we connect to it.
How is it different from a Static class?
- A Singleton class can inherit other classes and can also implement interfaces.
- A Singleton can be initialized lazily or asynchronously and loaded automatically by the .NET Framework CLR when the program or namespace containing the class is loaded. While a static class is generally initialized when it is first loaded.