What is the Singleton Pattern?
The Singleton Design Pattern is one of the most accessible and popular design patterns. This Design Pattern solves two problems at the same time.
- The Singleton Pattern helps you ensure that only one instance of a class exists. The most common reason you might want this is when you want to control access to a shared resource. There are plenty of classes where you might imagine it could get very confusing if there were different instances floating around your application.
- Provide a global access point to some data. Since you expose the single instance as a static method it can be called globally across your code.
Use the Singleton Pattern when a class in your application should have a single instance available to all clients; for example, a single database object shared by different parts of your application.
The Singleton pattern disables all other means of creating objects of a class except for the special creation method (getInstance()). This method either creates a new object or returns an existing one if it has already been created.
Structure of the Singleton Pattern
How to implement the Singleton Pattern in TypeScript
In order to implement the Singleton pattern in TypeScript, we need to understand how the pattern works first.
- Make the constructor of the class private. The static method of the singleton class would still be able to construct an instance of the class, but other classes may not.
- Add a private static field to the class to store an internal reference to the instance.
- Declare a public static creation method for retrieving/creating the singleton instance.
Here is a very quick example of a simple Singleton class.
1) The class holds a static private property called
#instance. This holds the instance of this class.
2) The static method
getInstance() checks if the
#instance is already set. If not it sets it and returns the value, otherwise it just returns the value.
3) Finally the constructor is marked as private. This restricts the class from being instantiated from outside of the class and will guarantee that we only have a single instance of the class.
4) Anywhere in the application you can now call
SingletonExample.getInstance() and it will return you with the instance if it exists or if It’s the first time it will create it and return it.
Testing the Singleton
It’s very easy to test if our Singleton class actually returns the same instance.
The Singleton Pattern is one of the easiest design patterns to understand. It’s a great introduction to how design patterns can improve your code and I would suggest reading more on the topic.
Thanks for reading. If you have thoughts on this, be sure to leave a comment.