Course contentsShow
← Software Engineering
Lesson 228 of 1,9337. Creational Design PatternsFree lesson

The Singleton Pattern: Intent and Structure

Learn what the Singleton pattern is, when it ensures a class has only one instance, and the basic structure of its implementation.

The Singleton Pattern: Intent and Structure

You'll learn what the Singleton pattern is, why you'd need only one instance of a class, and how it's basically organized.

What Problem Does Singleton Solve?

Imagine your application needs exactly one configuration manager, one logger, or one connection pool. Creating multiple instances would waste resources or cause conflicts. The Singleton pattern ensures a class has only one instance and provides a global point of access to it.

Think of it like a country's presidency: there's only one president at a time, and everyone knows how to reach that office when needed.

Intent

The Singleton pattern restricts a class to a single instance throughout the application's lifetime and gives clients a consistent way to access it.

Basic Structure

The pattern has three key structural elements:

  1. Private constructor — Prevents other code from creating new instances using new.
  2. Static instance variable — Holds the single instance of the class itself.
  3. Static accessor method — Provides global access to that instance, creating it if it doesn't exist yet (lazy initialization).

How It Works (Conceptually)

When client code asks for the instance:

  • The accessor checks if an instance exists
  • If not, it creates one (calling the private constructor)
  • If yes, it returns the existing instance
  • Either way, everyone gets the same object

This guarantees that no matter how many parts of your code request the Singleton, they all share the single instance.

Key Takeaway: The Singleton pattern ensures a class has exactly one instance by hiding its constructor, storing that instance statically, and providing controlled access through a static method—useful when one shared object must coordinate actions across the system.