Skip to content

Singleton Design Pattern

The Singleton design pattern ensures that a class has only one instance and provides a global point of access to it. This pattern is useful when you want to limit the number of instances of a class to one.

Typescript Implementation

Here’s an example of the Singleton design pattern implemented in TypeScript:

class Singleton {
  // Holds the single instance of the class
  private static instance: Singleton;

  // Private constructor ensures the class can't be instantiated from outside
  private constructor() {
    // Initialize any properties here
  }

  // Static method to provide access to the single instance
  public static getInstance(): Singleton {
    if (!Singleton.instance) {
      Singleton.instance = new Singleton();
    }
    return Singleton.instance;
  }

  // Example method for demonstration
  public showMessage(): void {
    console.log("Hello from the Singleton instance!");
  }
}

// Usage
const singleton1 = Singleton.getInstance();
const singleton2 = Singleton.getInstance();

// Output: Hello from the Singleton instance!
singleton1.showMessage(); 

// Output: true (Both are the same instance)
console.log(singleton1 === singleton2); 

Golang Implementation

Here’s an example of the Singleton design pattern implemented in Golang:

package main

import "fmt"

type Singleton struct {
}

var instance *Singleton

func GetInstance() *Singleton {
  if instance == nil {
    instance = &Singleton{}
  }
  return instance
}

func (s *Singleton) ShowMessage() {
  fmt.Println("Hello from the Singleton instance!")
}

func main() {
  singleton1 := GetInstance()
  singleton2 := GetInstance()

  singleton1.ShowMessage()

  fmt.Println(singleton1 == singleton2)
}

Python Implementation

Here’s an example of the Singleton design pattern implemented in Python:

class Singleton:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(Singleton, cls).__new__(cls)
        return cls._instance

    def show_message(self):
        print("Hello from the Singleton instance!")

# Usage
singleton1 = Singleton()
singleton2 = Singleton()

singleton1.show_message()

print(singleton1 is singleton2)

Applications of the Singleton Pattern

The Singleton design pattern is commonly used in scenarios where you need to ensure that a class has only one instance, such as: