Singleton
Intent
Ensures a class has only one instance and provides a global access point to it.
Problem
Several parts of the app need the same configuration or connection pool, and creating duplicates is wasteful or wrong.
Solution
Make the constructor private and expose a static method that creates the instance once and returns it afterwards.
Real-world analogy
A country has one official government. Whoever asks for “the government” reaches the same one.
Structure
Hover or tap a numbered role to highlight it in the diagram.
- 1Singleton — Singleton keeps a private static instance and a private constructor, so nobody else can create it.
- 2Singleton — getInstance() creates the instance on the first call and returns the same one afterwards.
- 3ClientA — Clients call getInstance() and always receive the same object.
Try it
Code example
public sealed class Config
{
private static readonly Lazy<Config> instance = new(() => new Config());
public static Config Instance => instance.Value; // thread-safe lazy init
private Config() { }
public string Get(string key) => Environment.GetEnvironmentVariable(key) ?? "";
}
// Prefer: services.AddSingleton<IConfig, Config>(); and inject IConfig.Applicability
Use Singleton when exactly one instance must exist (shared config, a single pool).
Use Singleton when you need stricter control than global variables.
How to implement
- Add a private static field for the instance
- Declare a public static creation method
- Implement lazy initialisation, thread-safe if needed
- Make the constructor private
- Replace direct construction with calls to the static method
Pros and cons
Pros
- Guaranteed single instance
- Lazy initialisation
Cons
- Violates Single Responsibility (manages its lifetime and does work)
- Hides dependencies and complicates unit tests
- Needs care in multithreaded code
- Often better replaced by a DI container singleton lifetime
Relations with other patterns
Check yourself
All modules must share one in-memory cache instance, created lazily on first use.
Saved in this browser only. Part of Creational patterns (0/5), Hands-on: patterns with live demos (0/5).