A few weeks ago, during a mentoring session that I hosted with a few colleagues from work, we ended up talking about good examples of using the Singleton Pattern in software development. As we discussed, it appeared that this pattern was in the “no-no” box, for some reason, and labeled as an anti-pattern. I think, however, that there are very good use cases for using it. This article shows how to leverage the Singleton pattern to optimize resources and prevent our applications from holding unnecessary class instances in memory.
The Singleton pattern is a creational design pattern with the purpose of enforcing the use of the same instance of a class in the application. It means that the investment of creating an instance of a class with this pattern is only paid once, making subsequent calls to methods of the same class faster. However, this means that that instance also shares any and all state, which makes it tricky to use in cases where the different calls to the class needs to have independent state management. That’s why, generally speaking, that using this design pattern is not taken into much consideration. Which is a shame, because I think it’s perfect to create and manage instances of service classes.
Service classes, also known as Managers or Handlers, are a set of classes that host behaviour methods. This definition is a little vague, on purpose, since the actual type of behaviour they’ll contain depends on which software layer it’s on (application, domain, infrastructure). Nevertheless, the key point is that they should be stateless, so instantiating several instances of the same service class is unnecessary and redundant. But that’s what I generally see happening when using Dependency Injection of service classes.
Creating instances of objects takes computational resources (mainly, memory), and they’ll live in-memory for as long as a request is being handled, before being garbage-collected or explicitly removed. If we have many uses of the same service class, instantiating it several times is a waste of resources and makes the process take more time to be handled than necessary, which is not very performant either.
That’s when I find that using the Singleton pattern shines, because after the first instantiation of the service class, the same instance will be used, instead of continuously creating new instances.