The Singleton Pattern

The singleton pattern is a software design pattern.

You can also call it the Highlander Principle: There can only be one!

But don't expect epic fights with swords and beheadings, that's only for the movie(s).

🧵👇🏻
1⃣ What is it?

As stated before, the singleton pattern is a software design pattern.

It restricts the instantiation of a class or a certain object to a single instance.

The pattern and its name are actually derived from the mathematical concept of a singleton.
In other words:

If you have a class A and make it a singleton, there can only be exactly none or exactly one instance per application.

Why none?

Because sometimes those singletons are also instantiated lazily to save resources, in case they are never needed!

👇🏻
2⃣ What is it good for?

Singletons are often used to coordinate actions across a system or to control resource access within one service.

You find singletons in state objects, facades or factories, which all often need nothing more than only one instance.
But singletons are not free of critique, as they implicitly create global state, which is often not the most desired thing to do.

Nevertheless, if you want to restrict the access to some resources, e.g., a singleton could be a great idea!
A specific database connection pool could be a great use case for a singleton, e.g.

Especially for many relational databases, connections can be pretty costly.

Opening a connection every time you want to fire a statement can potentially add a lot of overhead.
By maintaining a connection pool, and only one of it, you can ensure that everyone grabbing a connection uses the same pool.

And as creating multiple connections also costs time and resources, you only want to do it once and reuse them.

👇🏻
3⃣ Implementing a singleton in JavaScript

You can implement your singleton like you would implement any other class or object.

This example uses a class and only some basic, modern JS syntax.
By leveraging JS modules, you can restrict the visibility by controlling what exactly is exported.

In this case, only the function to retrieve a connection pool is exported, and thus the only interface to this module.

The constructor of the class is invisible,
... so that no one can instantiate another instance.

Another alternative would be to use an IIFE (immediately invoked function expression), which returns the one and only instance of an object.

This would also prevent anyone to invoke the logic once more and create another one!
You can follow @oliverjumpertz.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled:

By continuing to use the site, you are consenting to the use of cookies as explained in our Cookie Policy to improve your experience.