Today when we’re building a software we need to connect to other system such as database or external web services. In many cases we are lucky because we have a module or library that help us, but we pay attention on how we use it. A part the technology stack we use, we need to start to make a consideration about performance and memory usage. I think that we have to avoid to instance object indiscriminately especially for the critical part of the application. In most case to accomplish our purpose we use Singleton Design Pattern [ref.], but sometimes this is not sufficient because for example we need two or more instances of some module, class or library because for example we need to connect to multiple services so in these case we could use what i call Pooled Singleton Design Pattern.

Diagram for Pooled Singleton Design Pattern

In this schema ResourceHandler represent a class, module or library that in general handle some resource (Es. database connection, connection to external services) and we need only limited number instances of them. PooledResources throw his method getResource return a named instance of some ResouceHandler, this element is the key element to accomplish our purpose. So let’s start to realize this two element in practice using JavaScript and in particular Node.js stack technology.

Coclusion

In the code PooledResource has the responsability to build new ResourceHandler or retrieve one that is in our resourceHandlerInstances. In this way we can create some objects through its options and retrieve them everywhere in the application, we only import PooledResource and call getResource method passing it the name of the resource. If we have the need to separate the creational process of the object from the the retrieve and return instance of it we can create two separate methods createResource and getInstance and use it in separate manner. In this way we have control over the objects those populate our application and consequently the control over memory usage and performance. All the code reported in this article is present on GitHub.