Design Patterns

Pattern 1 of 23, Creational family

Singleton

Ensure a class has only one instance and provide a global access point to it.

The problem

Some resources (logger, configuration, connection pool) must be unique. If every module calls new Logger(), you end up with multiple instances, open files and inconsistent state.

The solution

Make the constructor private and expose a static getInstance() method that creates the instance on the first call, stores it, then always returns the same reference.

The pattern in action

  • Client
  • Key role of the pattern
  • Object
  • Data or state
  1. Client A asks the class for the instance.
  2. No instance exists yet: the class creates it and stores it.
  3. A receives instance #1.
  4. B makes the same request, elsewhere in the code.
  5. The instance already exists: nothing new is created.
  6. B receives exactly the same instance #1 as A.

An analogy

A country has only one official government: no matter who "asks" for it, it is always the same entity.

When to use it

  • A single shared resource (logger, config, cache)
  • Strict control over the number of instances
  • Expensive initialization that should run only once

Pros and cons

Pros

  • Guaranteed single instance
  • Lazy initialization
  • Centralized access point

Cons

  • Hidden global state โ†’ tight coupling
  • Hard to mock in tests
  • Multithreading pitfalls
  • Often better replaced by dependency injection (singleton scope)

Implementations

The same example, written idiomatically in each language.

Singleton in Python

singleton.py 15 lines
class Logger:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance.logs = []
        return cls._instance

    def log(self, msg: str) -> None:
        self.logs.append(msg)


a, b = Logger(), Logger()
print(a is b)  # True

Singleton in TypeScript

singleton.ts 17 lines
class Logger {
  private static instance: Logger;
  private logs: string[] = [];

  private constructor() {}

  static getInstance(): Logger {
    return (Logger.instance ??= new Logger());
  }

  log(msg: string) {
    this.logs.push(msg);
  }
}

console.log(Logger.getInstance() === Logger.getInstance()); // true
// Tip: with ES modules, "export const logger = new Logger()" is already a singleton

Singleton in Java

singleton.java 19 lines
public final class Logger {

    private Logger() {}

    // Holder idiom: lazy, thread-safe initialization without synchronized
    private static class Holder {
        static final Logger INSTANCE = new Logger();
    }

    public static Logger getInstance() {
        return Holder.INSTANCE;
    }

    public void log(String msg) {
        System.out.println(msg);
    }
}

// Most robust alternative: enum Logger { INSTANCE; }

Singleton in C#

singleton.cs 12 lines
public sealed class Logger
{
    private static readonly Lazy<Logger> _lazy = new(() => new Logger());

    public static Logger Instance => _lazy.Value;   // thread-safe by default

    private Logger() { }

    public void Log(string msg) => Console.WriteLine(msg);
}

// In ASP.NET Core, prefer: builder.Services.AddSingleton<ILogger, Logger>();

Singleton in PHP

singleton.php 20 lines
final class Logger
{
    private static ?Logger $instance = null;

    private function __construct() {}
    private function __clone() {}

    public static function getInstance(): self
    {
        return self::$instance ??= new self();
    }

    public function log(string $msg): void
    {
        echo $msg, PHP_EOL;
    }
}

var_dump(Logger::getInstance() === Logger::getInstance()); // true
// Laravel: $this->app->singleton(Logger::class);

Singleton in Go

singleton.go 24 lines
package logger

import "sync"

type Logger struct {
    logs []string
}

var (
    instance *Logger
    once     sync.Once
)

// GetInstance is thread-safe thanks to sync.Once
func GetInstance() *Logger {
    once.Do(func() {
        instance = &Logger{}
    })
    return instance
}

func (l *Logger) Log(msg string) {
    l.logs = append(l.logs, msg)
}

Frequently asked questions

What is the Singleton design pattern?

Ensure a class has only one instance and provide a global access point to it. Make the constructor private and expose a static getInstance() method that creates the instance on the first call, stores it, then always returns the same reference.

When should you use the Singleton pattern?

A single shared resource (logger, config, cache); Strict control over the number of instances; Expensive initialization that should run only once.

What are the pros and cons of the Singleton pattern?

Pros: Guaranteed single instance; Lazy initialization; Centralized access point. Cons: Hidden global state โ†’ tight coupling; Hard to mock in tests; Multithreading pitfalls; Often better replaced by dependency injection (singleton scope).