Saturday, March 19, 2022

SKP's GoF Design Patterns a Day - 02 - Singleton

[GitHub Repository for Code Samples]
https://github.com/sumithpuri/skp-code-marathon-phuket


Was going through the book ‘Head First Design Patterns’, came up with my own examples to understand them further. Try downloading the code and see if it helps you in comprehending these in a better way.
 

Singleton Pattern
Singleton Pattern defines a way to maintain only single instance of a class in the entire execution of a program/application and to provide a uniform way to access it. There are numerous methods which exist in which this pattern can be implemented. I have explained three most common scenarios here:
 
Fig. 3 : Singleton (Creational) Design Pattern - Class Diagram 
[Source : Wikipedia]

 

1. Eager Singleton [Sample Code]
The simplest singleton is the one in which the instance is created at class-load time, and stored in a static instance variable. A static getter method is then used to get this instance, when required. The instantiation of an object earlier than its first use might not be a recommended approach.

In the given example, MediaContract (Main Thread) works on an instance of the ProductionHouse (Singleton). The Singleton is instantiated at class-load time and maintained in the private static instance variable. getInstance() in ProductionHouse helps in retrieving the instance.

 
2. Thread-Safe Singleton (Most Common) [Sample Code]
To overcome the above drawback, the recommended approach is to instantiate the object at the first access time and also to make it thread-safe to prevent concurrent thread instantiation. The disadvantage of this method is poorer performance, as the method is synchronized.

As in the earlier example, the classes are MediaContract (Main Thread) and ProductionHouse (Singleton). getInstance() method is synchronized and the instance is created only if it is null.

 
3. Double-Checked Locking [Sample Code]
The disadvantage mentioned above can be critical for a highly accessed object in an application. To better this, the scope of the synchronized block is reduced to affect only the first access. This again has some disadvantages. I recommend reading on Initialization on Demand Holder Idiom.

The example remains the same, the difference being in the reduced scope of synchronisation within the getInstance() method and also that it affects only the first access and not subsequent accesses.
 

No comments: