Patterns of JavaScript: Singleton

Explained by video game levels

Arnold Abraham
5 min readDec 19, 2022
Image made by the Author via Canva.com

Singletons are handy when you need to coordinate system-wide actions from one place—for example, database connection pools.

Singletons reduce the need for global variables, which is critical in JavaScript because it limits namespace pollution and name collisions.

Other patterns, like Factory, Prototype, and Facade, are often implemented as singletons.

Singleton Pattern in a Nutshell

In the Singleton Pattern, there can only be one instance of an object at a time. A singleton is one instance of something.

When & Why Use the Singleton Pattern

Take a level manager as a good example.

The manager manages every level of the entire application. Very handy when you need to coordinate system-wide actions based on that level.

Initialize the player, spawn monsters, set up the UI, and so on. Besides, the player can only be in one playable level simultaneously. Hence it would be best if you had a single manager, not multiple.

Rule of thumb: Take the singleton if there can only be one of a kind.

Singleton Pattern Overview

--

--

Arnold Abraham

JavaScript, TypeScript and C#/.NET Tutorials/News/Best Practices by a German Software Engineer - Fun helps you to learn on the fly --> arnoldcode.com