Skip to main content

Singleton

Definition

A singleton is a design pattern that restricts the instantiation of a class to a single instance. This ensures that there is only one object of the class throughout the application, providing a global point of access to it.
It's commonly used in scenarios like managing game state, controlling audio, handling player input, or managing resources like textures and models, where having multiple instances could lead to inconsistencies, conflicts, or unnecessary resource consumption.

class GameManager {
private static instance: GameManager;
private constructor() { }

public static getInstance(): GameManager {
if (!GameManager.instance) {
GameManager.instance = new GameManager();
}
return GameManager.instance;
}

public startGame(): void {
console.log("Game started");
}

public endGame(): void {
console.log("Game ended");
}
}
GameManager.getInstance().startGame();

Why not just use static class?

Both singleton and static class provide a single point of access to their members, but there are important differences that make singletons a better choice in some situations:

  • Instance Control: A singleton allows for more flexibility because it is an instance of a class, meaning you can control when it gets created and destroyed. With static classes, static members exist for the lifetime of the application.
  • Inheritance and Polymorphism: Singletons are classes and can inherit from other classes or implement interfaces, allowing them to take advantage of polymorphism. Static classes cannot inherit from other classes, making them less flexible in object-oriented designs.
  • Lazy Initialization: Singletons can be instantiated lazily, meaning they are only created when needed. Static classes are initialized when the application starts, which can lead to unnecessary resource consumption if the class is never used.
  • etc.