Understanding The Core Aspects Of Singleton Design Pattern
In this article we are going to discuss the Singleton design pattern. In order to start the explanation, I will explain why these patterns do help for software engineers.
Think of an occasion the way you have been treated for a certain disease. For starters the doctor will come and ask some common questions and do some common tests before jumping into any predictions. Which means by their experience they have a certain pattern which they are used to in order to identify the disease.
Similarly in programming languages, developers have tested certain coding styles for several conditions and they have come up with practical solutions. These solutions have been tried and tested numerous times. So as the final output, they were able to come up with the design patterns. Which are much more efficient to use. Singleton design pattern is also one of them.
As a result, we may argue that these design patterns will provide a general answer to frequent challenges.
Design patterns are not considered as libraries which means these patterns can not be downloaded. We have to implement them in order to use.
These design patterns aren’t limited to a specific domain, and if you’re familiar with them, You’ll be able to effortlessly adapt to them.
According to the Book Design Patterns — Elements of Reusable object oriented software, the design patterns have been divided into three type as
- Creational Patterns
- Structural Patterns
- Behavioral Patterns
Creational Patterns
Creational design patterns are concerned with the way of creating objects. When a decision must be made during the instantiation of a class, these design patterns are used (i.e. creating an object of a class). Trying to create objects in a manner suitable for a situation.
Structural Patterns
Structural design patterns are concerned with how classes and objects can be composed, to form larger structures. It Simplifies Structure by identifying relationships.
Behavioral Patterns
Design patterns which identify common communication patterns between objects and realize these patterns.
Types of Design patterns and examples
Singleton Design Pattern Explained
Singleton pattern comes under creational design patterns. In singleton pattern what happens is, it makes sure only one instance of the class per container is created. This instance has global point access to it.
So in the singleton design pattern we can not create numerous instances from a class.
Occasions where singleton design pattern being used.
- Used in logging, caching, thread pools, configurations settings etc.
- Used in multi threaded and database applications.
Advantages of using Singleton design patterns
- Save memory because a single instance is used regarding to a specific class
- Efficiency is improved, because after creating the instance the same instance can be used so no need to wait for re creation.
UML Representation of Singleton Design Pattern
Important facts that should be considered when implementing a singleton pattern.
- If you are implementing a singleton pattern then you should not take any arguments when creating the instance. (Taking arguments in not a preferred way of executing singleton)
- Very hard to do unit tests since there are no instance variables and no references to create. So should not overkill the singleton pattern and use the pattern if only necessary.
Design approaches of Singleton design pattern
In this article we are going to discuss the following design approaches of singleton pattern.
- Eager initialization
- Lazy initialization
- Double checking initialization
Eager Initialization
Simplest way of creating the singleton design pattern. Instance of the singleton class is created when the class is loaded to the memory because of the static initializer.
Note: The instance of the class will be created even though it is not in use.
Below I have included the implementation code.
In this above example you can identify that in both print statements the same object is displayed.
In this approach you can see that the instance is being created as a static initializer, which means at the start of the program the instance will be created.
This technique is thread-safe, however there is a risk of resource leakage if this pattern is used. Because the object is created even when it is not in use.
Lazy Initialization
An object is created only when it is required in this implementation (So the resource wastage is prevented).
The object will not be created at the point of start, here according to the situation getInstance() method will be called and it will first check whether the object is null if the object is null then it will create the instance if not return the created instance.
The Object will not be created unless it is absolutely necessary from this approach.
Note : This approach is not thread safe because multiple threads can access the method at the same time and it will lead to creation of multiple objects. Therefore this approach can only be used in a Single threaded environment.
Below I have included the implementation code.
In this approach also you can identify that in both print statements the same object is displayed.
Double checking Singleton Approach
This method is known as double checking since the issue of resource leakage is minimized when using lazy initialization. However, the fundamental problem with lazy initialization is that it is not thread safe. As a result, a double check is performed in double checking pattern in order to keep the design pattern thread secure.
Here is the implementation of double checking singleton pattern.
So, in this double-checking singleton approach, you can see an if condition in Figure 9 where the constructor is being built. This if condition is used because reflection API constructs can be used to build objects of classes. So, in order to prevent instances from being created using the reflection API. In the constructor, we verify and throw an exception if someone tries to do so.
You can see that a synchronized block is used in the get instance method, and that the method also has two if conditions. The main advantage of synchronized is that once a thread enters a block, no other thread can access it.
So, in the first if condition, it will see if an object has been created, and if not, it will proceed to the synchronized block (thread 1). Other threads cannot access the synchronized block while thread1 is performing operations inside it. The instance will be returned once the object has been created. The waiting thread (thread 2) will then be able to access the block, but there is yet another if statement, this time checking whether an object has been created. Since an object has been created, the authorization to create another object will be denied, and the same instance will be returned.
Note: At the method level, some developers use the synchronized keyword. This is something that should be avoided at all costs. Because using the synchronized keyword at the block level disables the entire procedure and reduces performance.
Mostly this Singleton pattern is used when creating a database connection.
Efficiency of the Singleton pattern.
By using the below code segment you will be able to understand the efficiency of the singleton pattern.
In this code segment what I have done is creating two “DobleCheckingPattern” class type variables and assigning the instance for them. I record the time it takes to create and assign the instance using start and end long type variables.
What do you think the output would be?
Here I have included the screenshot of the resulting output.
This design pattern will cut down on the time it takes to create objects. As you can see, it took a bit of time initially, but there was no time used after that. With the help of this design pattern, efficiency is increased. However, we should be more cautious when using the singleton design because there are specific situations where it might bring complications. I discussed them during the initial part of this article.
Hope you had a clear idea about singleton design pattern.
Hope you got a clear and better understanding regarding the design pattern related to java. Hope to see you again in a future article, Thank you for reading !
Here I have included the sources which I have referred.
(4231) Power of Singleton Design Pattern | Design pattern you MUST know — YouTube
Singleton Design Pattern | Introduction — GeeksforGeeks