The singleton pattern::the good, the bad, and the ugly
Published July 05, 2015
We use the singleton pattern in order to restrict the number of instances that can be created from a resource consuming class to only one.
Resource consuming classes are classes that might slow down our website or cost money. For example:
- Some external service providers (APIs) charge money per each use.
- Some classes that detect mobile devices might slow down our website.
- Establishing a connection with a database is time consuming and slows down our app.
So, in all of these cases, it is a good idea to restrict the number of objects that we create from the expensive class to only one.
Use a singleton pattern to restrict the number of objects to only one!