Singleton Pattern

PUBLISHED: 2026-07-21
AUTHOR: MANUEL PRIETO
Design Patterns

Singleton is a creational design pattern that lets you ensure that a class has only one instance, while providing a global access point to this instance.

Purpose and Use Case

Use the Singleton pattern when a class in your application must have only a single instance available to all clients (for example, a database connection object, a centralized logger, or a global configuration manager).

Pattern Structure

Regardless of the programming language (TypeScript, PHP, Python, C++, etc.), the conceptual structure of the pattern relies on three pillars:

  1. Private constructor: Prevents other objects from using the new operator directly.
  2. Private static attribute: Stores the reference to the single created instance.
  3. Public static method (getInstance): Acts as a global access point that initializes the instance on first request and returns it on subsequent calls.
Cargando diagrama...

How It Works

  1. Request: The client calls Singleton.getInstance().
  2. Verification: The class checks whether the static variable instance already holds an object.
  3. Lazy initialization: If the instance does not exist (null or undefined), it privately invokes the constructor and assigns it.
  4. Return: Returns the existing instance, ensuring a single shared object across the entire application.

Real-World Implementation Examples