Design Patterns In TypeScript — Singleton
How to restrict the instantiation of a class to one object
Singleton is one of the most used design patterns in software development. In this post, we will learn how to implement this pattern in the context of web development using TypeScript.
What is Singleton?
The authors of the book Design Patterns: Elements of Reusable Object-Oriented Software defines Singleton Pattern as:
A singleton class is a class that has a single object and that unique object constitutes a global facility for all clients.
Basically, the singleton pattern forces you to get an instance of the class via a class method or a getter. Therefore, instead of creating an instance using the new
operator, all clients will access the instance created and stored by the Class.
In this particular situation, you will only have one instance of the class in your application and you can be sure that all clients will use the same instance properties. This is a good way to reduce memory consumption as we will only have one object in memory for this instance of the class.