Introduction to Parametric Singleton Pattern

Most of us heard about Singleton pattern. This pattern makes sure that there exists only one instance of a class in the system at a given time. This will make sure that all clients are served by a single instance by providing global point of access to it. In certain situations, we might need to extend this pattern making sure that only one instance exist for a given set of parameters. This pattern is called as parametric singleton pattern. I am going to discuss this pattern in deep followed by an example.

Introduction:

Parametric singleton pattern can be used in cases where we want only one instance of a class for a given set of parameters. For example, instance that will write data to a file need to be unique for a given file name. That too, its waste of maintaining objects with same kind of data in memory. The best solution to handle this kind of issue is using of this pattern. In this pattern, class will be declared as sealed, so that it cannot be sub classed. And constructor will be made private, so that other classes cannot create an instance of it. Than, we will keep track of instances created by this class using data structures like ArrayList or HashSet.  If an instance exists with that parameters, we will just return the reference of that object else we will create a new object and return it.

This pattern works similar to a cache management pattern. In cache management, if the required object is not present in the cache, it will create one and returns else it will return the object present in the cache.

Scenarios applicable for using this Pattern:

  • If we want only one instance of a class for a given parameters.
  • If the instance need to be accessible from a global and well-known point.

Benefits of using this Pattern:

  • We can control creation of instances based on parameters.
  • We can reduce unwanted resource utilization by duplicate objects like resources of kind file handles, sockets etc.

Implementation:

Create a new console application in VS 2008 and name it as ParametricSingeltonExample. Add the below class definition to program.cs as shown below:

Now create instances of above class in Main method as shown below:

2.jpg

Run the application. Since instance1 and instance3 are having same parameter values, it will have same reference. Updating instance1 value will reflect in instance3 object.

Drawbacks of this Pattern:

  • Instances are stored in a HashSet. There is no mechanism to release those objects and allow them to be garbage collected.
  • We won't be having control over who accesses the instances.

I am ending up the things here. I am attaching source code for reference. I hope this article will be helpful for all.