Learning Singleton Pattern
The Singleton Design Pattern
The singleton pattern is a creational pattern that produces a single instance of an object throughout an app. Singletons achieve this by restricting how objects are created and making them globally accessible. This is useful in circumstances where multiple instances of an object aren’t desirable. For instance, it may not be best to create a database connection each time you need to access the database. Instead, you may keep a single instance of the first connection and make it available to any class that needs it. The same is true for loggers, caches, thread pools, and some other object types.
You only need one ID or passport to identify yourself. You don’t have to create a new copy each time you need to show your ID to an official. You use the same passport whenever you need it. In the same way, you don’t need a new trash can each time you need to dispose of an item — you use the same trash can over and over until you can’t use it anymore. These are good examples of the singleton pattern at work around you.
Learning When to Use Singletons
Singletons are helpful when it’s expensive to create an object. If you can safely use one instance of a resource-intensive object throughout your app, you probably should make it a singleton to avoid creating it multiple times. This also prevents code duplication since there’s only one place to access singletons. Having a single instance of an object means you reduce the amount of memory your app uses. Access to singletons is better controlled since you only need to look in one place or class to find and manage its creation. Making objects available globally provides easy access to objects that require it.
Disadvantages of the Singleton Pattern
This pattern could lead to a memory leak if not properly handled or disposed of after use. Providing singletons globally can make it difficult to track how they’re used in the app. Singletons can also be difficult to test. Extra steps are necessary to make singletons thread-safe, increasing the app’s overall complexity. Singletons promote tight coupling and hidden dependencies, which go against the SOLID principles.
In the upcoming segment, you’ll learn how to implement the singleton design pattern in an e-commerce app. Take a moment to think about how this pattern can be used in your app, then proceed to the demo.