Design Patterns: Singleton

Please see my other Design Pattern articles.

Ensuring single instance use during instantiation.

0-mvc-singleton

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.

1-mvc-singleton

Next, I have created a test Controller in which I illustrate the results when I attempt to instantiate two Chat objects.

2-mvc-singleton

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.

3-mvc-singleton

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s