Singleton Pattern
We start with a design pattern called a singleton. It is one of the most well-known patterns, and therefore it is a good starting point.
Singleton restricts a class to have just one instance and ensures that it is globally accessible. It might come in handy when you need to manage something from across your whole application.
The term singleton comes from math and means a set with exactly one element
By design, singletons create an instance
of a class if it does not yet exist. Otherwise, they return the reference
to an existing instance.
Now, every time we call Singleton.getInstance()
, we get the same object.
The code above looks fine at first glance, but it has some issues. Nothing restricts us from calling the Singleton constructor directly. This is when the TypeScript
might come in handy.
By making the Singleton constructor private, we can only call it from within the getInstance
function.
Another approach that we can take is to return an instance straight from within the constructor.
The above makes it a bit less transparent because someone might not be aware that the constructor returns the same object every time.
Singletons have a lot in common with global variables. This is also why they often are discouraged because they share their disadvantages as it might make your application less readable
. Whether we consider singletons good or bad, they are one of the fundamental design patterns. Understanding them might one day come in handy. Even if you don’t decide to write them yourself, you might encounter them in some applications.
Resources
Last updated