| Type | Creational |
| Purpose | Ensure a class allows only one object to be created, providing a single point of access to it. |
Description
The purpose of the Singleton pattern is to ensure that there is only one instance of a class, and that there is a global access point to that object. The pattern ensures that the class is instantiated only once and that all requests are directed to that one object. In the Singleton pattern, it is the class itself that is responsible for ensuring this constraint, not the clients of the class.
Overview
| Singleton | Defines an Instance operation that lets clients access its unique instance. Instance is a class operation. Responsible for creating and maintaining its own unique instance. |
First Implementation
This is a traditional implementation of the Singleton pattern in C#:
public sealed class SingletonPattern
{
private static volatile SingletonPattern? instance;
private static readonly object lockObject = new();
private SingletonPattern () {}
public static SingletonPattern Instance
{
get
{
if (instance == null)
{
lock (lockObject)
{
if (instance == null)
{
instance = new SingletonPattern();
}
}
}
return instance;
}
}
}
// usage:
// var singleton = SingletonPattern.Instance;
Second Implementation
Because .NET guarantees thread-safe type initialization, we can use static initialization instead:
public sealed class SingletonPattern
{
public static readonly SingletonPattern Instance = new SingletonPattern();
private SingletonPattern() {}
}
// usage:
// var singleton = SingletonPattern.Instance;
Summary
It is important to note that the constructor should be declared private to prevent clients from directly creating instances of the class.
Robert Nystrom has a chapter on Singleton here.
For more information, please see here.