Patterns of JavaScript: Singleton

Explained by video game levels

Arnold Abraham

--

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

Image made by the Author

This pattern involves:

  • Singleton: Gets the unique level instance with getInstance() and creates and manages the instance object.

Example 1: Singleton Basics With a Level Manager

IIFE (Immediately Invoked Function Expression) is key to this pattern.

A Singleton object is implemented as an anonymous function, which executes immediately after being encapsulated in brackets, followed by two other brackets.

Anonymous because it doesn’t have a name.

The getInstance() method returns the only instance of the object while maintaining a private reference that isn’t visible to anyone outside.

--

--

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