Singleton Pattern

This pattern comes under the creational patterns which are widely used in programming constructs. This pattern provides the best way to create objects.

In simple words, the Singleton pattern provides the single instance of the class throughout the lifecycle of the execution. Singleton patterns consist of the single class which create the Instance of that class, a single instance used by the application throughout the lifecycle.

Explanation

Example and Implementation

UML Diagram

UML Diagram

Code

First Implementation

Second Implementation

Second implementation is the threadsafe Implementation in which threads acquire the lock to the Singleton class and then they check the condition one-by-one; the first thread comes to it to check the condition and it finds the field is null and condition is true so they create the instance. Second thread comes then if condition is false it returns the previously created object. In Java we use synchronization and in C# we use lock and a Mutex algorithms to acquire the lock. Here is the simple implementation of the threadsafe method using the C# lock mechanism,

code
Third Implementation

Third implementation is quite lazy and tries to get thread safety using the double locking mechanism. The one and only single phrase with respect to that implementation is “We don’t use that implementation because of the double locking mechanism which is too expensive,” like in java, synchronization is much too expensive from the performance perspective. So that implementation is not good enough.
code

Fourth Implementation

The fourth implementation is extremely simple using static field without loc, in which we simply declare the static field; plus, with initialization this happens with the help of the static constructor. As we know, the static constructor is called once in the lifecycle of the application so when the constructoris is called the field is initialized once right after the constructor calls, so there is no chance that this method won't provide the thread safety after all. This implementation also provides the thread safety which is an extremely simple way to achieve this without even using any locking mechanism.

code

Conclusions

The singleton pattern is widely used in Software Architecture. Most of the time there is a need for Singleton when we write the system application which accesses the device drivers. There are four implementations of the Singleton Pattern. The abstract factory and factory builder prototype design patterns use Singleton for their inner implementation. Singleton provides thread safety access to a single object. There is no need to make the object of a Singleton class; only class name is responsible to get the fully initialized object.