Ensuring single instance use during instantiation.
Every so often in development, a business rule dictates that instantiation of a certain type produce only one instance during the lifetime of the application.
The Singleton design pattern, one of the Creational Patterns, ensures that regardless of many instantiations of a class may be attempted, only the first will produce a unique object.
To illustrate this pattern, I will pretend that I have a website with a chat feature that only should have one instance running to service the many requests it may receive during the lifetime of the application.
I have integrated into my Chat class the pattern to ensure that will different pages of my site attempt to instantiate a Chat instance, only the first attempt will return a unique object.
The heart of this pattern that ensure only one unique object is returned is the combination of a static instance and the “GetInstance()” method use to create the first instance which checks first to see if the class attributes has already been created before it attempts to create a new one.
Also, I record the date/time of the first object instantiation for debugging purposes and perform a test to see if instance1 and instance2 are the same object.
Next, I have created a test Controller in which I illustrate the results when I attempt to instantiate two Chat objects.
As you can see, the date/time variable recorded during the first instantiation is identical after both attempts.
This illustrates how the pattern only returned a new object the first time and ignored the second attempt.