Singleton Design Pattern (Java)

Anojaa Gnaneswaran
2 min readMar 14, 2022

--

Design patterns represent the best practices used by experienced object-oriented software Engineer. Design patterns are solutions to real world problems that software developers faced during software development.

It is Introduced in 1994 by four authors Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides published a book titled,”Design Patterns — Elements of Reusable Object-Oriented Software” which initiated the concept of Design Pattern in Software development.These authors are normally known as Gang of Four (GOF). According to these authors design patterns are primarily based on the following principles of object orientated design.the design pattern divided into three type.

  1. Behavioural
  2. Creation al
  3. Structural

Singleton pattern

It’s a most common used design pattern in programming.singleton mean one instance for container also It is abuse design pattern “because people have cloudy view about singleton pattern and Implement the way they will right.If you have java programmer it is one instance for and JVM.when we using much argument better to go factory pattern.

singleton usually not over killed because Really hard to unit test.”No Instance variable and reference to create “ we only use singleton where is it possible to use.

First we go with sample example of singleton design pattern.here I am going to Initialized the DBmanger class.Here we using private constructor for anyone can not create instance from that.

DBManager class

Now we going to create Application class for this pattern (main class).

Application class

Now I will write the code for manual invoking the constructor,but it occur some sort of problem.lets see the code.

Manual invoking for constructor

Above code It will create problem,There is a problem when the first thread come here and check it is Null, It will try to create assign the value into dbmanager. Same time second thread will come and ask is this null,,the Instance still not created because it’s on creating stage.so second thread also come in to process. it called as” thread Not safe”. avoid this type of edge case we will using double checking singleton principle.

Double checking principle singleton pattern (Synchronized)

In above code in the 12th line if we use synchronized method ,it will gives performance hits,so that we will using static method here.

I hope you got basic Idea about Singleton pattern.

Happy Coding!

Reference

  1. https://www.youtube.com/watch?v=g7RfBhO-rhU&list=PLD-mYtebG3X86i3uyAXwZKfVtUy2gMDdo

--

--

Anojaa Gnaneswaran

Faculty of IT, University of Moratuwa, Associated Software Engineer at Virtusa