Singleton Pattern
Control construction and expose a shared instance, with explicit limits on what single means.
· Last updated: 2026-11-05 · 10 min read
Overview
Several parts of a program use the same read-only catalog. If each place builds its own copy, the same table ends up existing several times over. Since there is no reason to build a new object each time, the program can keep just one and restrict the construction path so that everyone reaches that object.
The Singleton pattern restricts a class to one instance and provides an access point to it. The constructor is hidden, and callers receive the same object through Instance.
UML
In the diagram, callers reach AppCatalog.Instance. Its constructor is private, and a static Lazy<AppCatalog> creates the instance on first request. Nothing else can construct it.
History
GoF cataloged Singleton as a creational pattern in Design Patterns in 1994. It restricts a class to one instance and provides access to it.1
Why use it?
Singleton is convenient. Hiding dependencies behind global access, though, damages coupling and causes frequent trouble. Once callers are tied directly to AppCatalog.Instance, slipping in a test double or splitting configuration per user becomes difficult, and mutable state lets one call's change spill into another. When that convenience hardens into a habit of adding more global state, it turns into an anti-pattern. Reusing one instance and making it globally accessible are different decisions; each needs its own justification.
The "one" mentioned above is scoped to the static field in the same load context of this runtime. Nothing wider is implied. With several server processes, each gets its own, so this cannot serve as a mechanism against duplicate execution of distributed work.
Example
In the example, the shared object is AppCatalog, which holds nothing but a version string, and the check is whether the two references obtained are the same.
using System;
using System.Collections.Generic;
using System.Linq;
Console.WriteLine(ReferenceEquals(AppCatalog.Instance, AppCatalog.Instance));
// Own construction so callers do not create separate catalogs.
sealed class AppCatalog
{
private static readonly Lazy<AppCatalog> shared = new(() => new AppCatalog());
private AppCatalog() { }
// Lazy<T> synchronizes initialization; callers using this static property receive the same object.
public static AppCatalog Instance => shared.Value;
public string Version => "v1";
}
TrueIn the example, what Lazy<T> synchronizes is initialization. That guarantee covers initialization alone; it does not mean that mutable behavior layered onto the object later becomes thread-safe too.
An extended example
The wider example asks whether a single instance results even when several tasks reach it for the first time at the same moment. The catalog stays read-only in this example.
using System;
using System.Collections.Generic;
using System.Linq;
var tasks = Enumerable.Range(0, 8)
.Select(_ => System.Threading.Tasks.Task.Run(() => AppCatalog.Instance)).ToArray();
var values = await System.Threading.Tasks.Task.WhenAll(tasks);
Console.WriteLine(values.All(value => ReferenceEquals(value, values[0])));
Console.WriteLine(values[0].Version);
// Own construction so callers do not create separate catalogs.
sealed class AppCatalog
{
private static readonly Lazy<AppCatalog> shared = new(() => new AppCatalog());
private AppCatalog() { }
// Lazy<T> synchronizes initialization; callers using this static property receive the same object.
public static AppCatalog Instance => shared.Value;
public string Version => "v1";
}
True
v1Concurrent access still yields a single object, but the guarantee covers only the calls that share the same static field. The example confirms nothing beyond that scope. If configuration has to differ per user, check first whether that sharing scope matches the requirement.
TypeScript example
The same split carries over to TypeScript, where construction and the access point gather inside AppCatalog. Every caller then uses the same catalog and takes the shared object from instance instead of constructing a new one.
// Own construction so callers do not create separate catalogs.
class AppCatalog {
static #shared: AppCatalog | undefined;
readonly version = "v1";
private constructor() { Object.freeze(this); }
// Create on first synchronous access and reuse the object within this module instance.
static get instance(): AppCatalog {
return AppCatalog.#shared ??= new AppCatalog();
}
}
const first = AppCatalog.instance;
const second = AppCatalog.instance;
console.log(first === second);
console.log(first.version);true
v1Here the sharing scope is the same JavaScript module instance, and Object.freeze(this) pins the version value. The private constructor is a restriction at type checking, not a security boundary against JavaScript callers.
Share the object without global access
The earlier examples assumed global access. To share an object without it, create the shared object once where the program is assembled, then pass it as an argument to the function that uses it. Dependency injection (DI) is how something needed is received from outside, and it needs no separate container. The function below never looks up a global catalog, so a test can pass a different value as it is.
C#
using System;
ICatalog shared = new Catalog("v1");
// Receive the dependency instead of looking up a global object.
string Heading(ICatalog catalog) => "catalog " + catalog.Version;
Console.WriteLine(Heading(shared));
Console.WriteLine(Heading(new Catalog("test")));
interface ICatalog { string Version { get; } }
sealed record Catalog(string Version) : ICatalog;TypeScript
type Catalog = Readonly<{ version: string }>;
const shared: Catalog = Object.freeze({ version: "v1" });
// The caller decides whether to reuse the object or supply a test value.
const heading = (catalog: Catalog): string => "catalog " + catalog.version;
console.log(heading(shared));
console.log(heading(Object.freeze({ version: "test" })));catalog v1
catalog testReusing one object is a lifetime policy, while retrieving that object globally from anywhere is a separate matter. Even if DI has settled the shared lifetime, concurrent access to mutable state and responsibility for releasing resources still have to be decided separately.
Microsoft: Dependency injection guidelines
From Singleton to a generic base class
In the small example, Singleton.GetInstance() is the access point that returns the same object, while the private constructor prevents callers from using new Singleton(). The class names expose the pattern before business names enter the picture. Naming the class AppCatalog leaves that construction-and-access relationship unchanged.
When several classes repeat the same lazy construction code, a Singleton<T> base can hold it. T is the concrete shared class: Catalog and Settings each inherit with their own type, and the base keeps a separate Lazy<T> for each closed generic type. Each concrete class supplies one fixed factory, so its constructor can remain private.
C#
using System;
using System.Threading;
Console.WriteLine(ReferenceEquals(Singleton.GetInstance(), Singleton.GetInstance()));
Console.WriteLine(ReferenceEquals(Catalog.GetInstance(), Catalog.GetInstance()));
Console.WriteLine(Catalog.GetInstance().Name + "/" + Settings.GetInstance().Name);
// TYPES
sealed class Singleton
{
private static readonly Lazy<Singleton> shared = new(() => new Singleton());
private Singleton() { }
public static Singleton GetInstance() => shared.Value;
}
abstract class Singleton<T> where T : Singleton<T>
{
private static readonly object gate = new();
private static Lazy<T>? shared;
protected Singleton() { }
protected static T GetSingleton(Func<T> create)
{
Lazy<T> holder;
// Register one holder per closed type; Value performs the actual construction.
lock (gate)
holder = shared ??= new Lazy<T>(create, LazyThreadSafetyMode.ExecutionAndPublication);
return holder.Value;
}
}
sealed class Catalog : Singleton<Catalog>
{
private Catalog() { }
public static Catalog GetInstance() => GetSingleton(() => new Catalog());
public string Name => "catalog";
}
sealed class Settings : Singleton<Settings>
{
private Settings() { }
public static Settings GetInstance() => GetSingleton(() => new Settings());
public string Name => "settings";
}True
True
catalog/settingsTypeScript
class LazySingleton<T> {
#state: { tag: "new" } | { tag: "creating" } | { tag: "ready"; value: T } | { tag: "failed"; error: unknown } = { tag: "new" };
constructor(private readonly create: () => T) {}
getSingleton(): T {
// A separate state can cache undefined as a valid factory result.
if (this.#state.tag === "ready") return this.#state.value;
if (this.#state.tag === "failed") throw this.#state.error;
if (this.#state.tag === "creating") throw new Error("Recursive initialization");
this.#state = { tag: "creating" };
try {
const value = this.create();
this.#state = { tag: "ready", value };
return value;
} catch (error) {
this.#state = { tag: "failed", error };
throw error;
}
}
}
class Singleton {
static readonly #shared = new LazySingleton(() => new Singleton());
private constructor() {}
static getInstance(): Singleton { return Singleton.#shared.getSingleton(); }
}
class Catalog {
static readonly #shared = new LazySingleton(() => new Catalog());
readonly name = "catalog";
private constructor() { Object.freeze(this); }
static getInstance(): Catalog { return Catalog.#shared.getSingleton(); }
}
class Settings {
static readonly #shared = new LazySingleton(() => new Settings());
readonly name = "settings";
private constructor() { Object.freeze(this); }
static getInstance(): Settings { return Settings.#shared.getSingleton(); }
}
console.log(Singleton.getInstance() === Singleton.getInstance());
console.log(Catalog.getInstance() === Catalog.getInstance());
console.log(Catalog.getInstance().name + "/" + Settings.getInstance().name);true
true
catalog/settingsThe base retains the first factory, and Lazy<T> synchronizes its execution. It does not use the new() constraint, which would require a public constructor. This Lazy<T> caches a factory exception; mutable operations on the created object and global dependencies remain separate concerns. TypeScript erases type arguments at runtime, so its example gives each concrete class its own lazy holder.
The official references describe the type-parameter syntax and library contracts.2
Related reading
Footnotes
- Gamma, Helm, Johnson, Vlissides. Design Patterns (1994). Publisher record. Creational patterns, Singleton. ↩
- C# generics; TypeScript generics; C# generic static members; Lazy<T>; TypeScript generic static members ↩