Design patterns part 1 — Singleton pattern

Ramsunthar Sivasankar
Nerd For Tech
Published in
6 min readJun 27, 2021

--

(source: https://www.hojjatk.com/2014/08/design-patterns.html)

This is a new topic that I am going to talk about. Most of the developers might heard about design patterns or maybe that word. In interviews also you will be asked about design patterns even it for an Associate position.

What is Design Pattern?

It is a general solution for common problems that occurring in software design and it is more like a pre-designed template that we can customize to solve the problem. You can’t directly convert into code because it is just a general concept for solving specific problems. For easier understanding, you know that Dollar is the standard currency for the global economy likewise these design patterns are the standard best practices in the software design and through this developers are able to communicate using well understood term for interactions of the software design. Most importantly design patterns are language independent. In 1994, Erich Gamma, John Vlissides, Ralph Johnson, and Richard Helm published a book called “Design Patterns: Elements of Reusable Object-Oriented Software” which explained about the design patterns to programming and it consist of 23 design patterns solving various problems of software design and it also known as “GoF book

Why do we need Design Pattern ?

We can reuse these design patterns in different projects. By using this we can give solution which helps to define the architecture of the system. We can use it in our projects without a fear because they are based on the expertise and experience of professional software developers and we can build a better system because design patterns provide a proper clarification to design the system architecture.

Classification of Design patterns

Types of Design Patterns (source: http://www.algorithmforum.com/2018/08/design-patterns-software-design-pattern.html)

There are mainly 3 categories in design pattern such as creational, structural, and behavioral as I showed in the above image.

Creational patterns — This pattern provide object creation mechanisms in a controlled manner that helps to reduce the code complexity.

Structural patterns —This explains how to combine objects and classes into bigger structures while maintaining flexibility and efficiency.

Behavioral pattern — This pattern is all about the communication between objects.

So this is basic of design pattern and I’ll be discussing some of these design patterns in the upcoming article as well and this is going to be a series of article.

Singleton Pattern

What is “Singleton design pattern”, It actually means one instance(unique instance) per container and if you are using Java then one instance per JVM. There may be a case where we have to use only one instance of a particular object in a project. So this concept allows us to create and use that one instance throughout the project. For example, Lets say person X has an account in ABC bank and he/she withdrawing a certain amount of money from his/her account at the same time person Y depositing some money to person X’s account. Note that this transaction happening in the same time. So if we didn’t follow singleton design pattern here, It leads to data inconsistency. So if we use one instance of this account object, then this transaction will happen smoothly. We use this pattern while connecting database as well because there will be multiple query updates to a single table at a time.

class diagram of singleton pattern

There are certain things we should follow while implementing this design pattern,

  • We should create a static variable for the instance and it should not take any arguments.
  • We should create a private constructor and it prevents creating instance of singleton class from outside the class
  • We should create a static method to provide a global access point for the singleton object.

Lets take a look at the code,

Early Initialization

as you can see from the above code, we create an instance (instance) from the Singleton class with a private constructor and public method (getInstance())to give global access to that instance.

Note — volatile keyword is used to keep the data consistency in the multi-threads scenario. Click here to learn more about usage of volatile.

To test, I have created a class called Application and assigned two different variable to use the singleton object. If I run this I’ll get the output as follows,

singletonPattern.Singleton@3830f1c0
singletonPattern.Singleton@3830f1c0

Even though I assigned to two different variable and called in different time, it still access the same instance because its singleton. What happens in the first file (Singleton_1.java) is the instance was created as soon as the application loads and this is called “Early Initialization”. There may be a case where we don’t need the singleton object all the time. So at that case, this will be a disadvantage. Lets see how we can overcome this.

Lazy Initialization

In here we don’t create the instance at the beginning as you can see from the code below (line number 3). So when we invoke getInstance() method, it checks(line number 9) whether there is an instance already created or not. If already created it returns that instance(line number 12) and if not it will create a new instance(line number 10). Which means it only creates when we request and this is known as “Lazy Initialization

The problem in here is if there are two threads coming in concurrently, first thread goes to line number 9 and check whether there is a instance created or not and since this is the first thread it will go to line number 10. While the instance is been creating the second thread comes to line number 9, at this point the instance is not created yet so it will allows the second thread to line number 10. So this is NOT thread safe. There may be a case where multiple threads may create instance like this. To avoid that we can do some changes in the code and lets see how.

Lazy Initialization — with Thread safe

Lets take the same scenario as before (two threads), So the first thread will come to line number 9 and check whether the instance is null or not, since its null it will go to line number 10 and acquire the lock then it will go into the synchronized block and check again for existence of the instance and it will create the instance on line number 12. Now the second thread goes to line number 9 and it will allow because the instance creating process is going on which means its still null. But when it hits the line number 10, it will stop the second thread to move further because the lock is already acquired by the first thread. So the second thread can only go further after the first thread releases the lock (by completing the execution). Its known as “double checked locking”. So the second thread will be allowed by the synchronized block and inside that it checks again and at that time instance is not null so it will return the same instance (line number 16).

Some people will use the synchronized keyword in the access method(next to static keyword in getInstance method). You can do that but you should not because this is small example but in the actual project there may be lot of codes should be executed within that method so at that time if there multiple threads coming concurrently, each threads coming after the first one have to wait more time to access the method. So it is always best to put the synchronized block wherever its needed.

So this the Singleton pattern and I hope you will understand this. I will be discussing about Factory pattern in the next article.

--

--

Ramsunthar Sivasankar
Nerd For Tech

MSc student of Greenwich University || Software Engineer