Java Singleton Design Pattern

Here you will learn about java singleton design pattern with example.

 

What is Singleton Design Pattern?

  • Defining a class that can have single instance and provides a global access point to get the instance.
  • This design pattern is mainly used in multi-threaded and database applications.
  • It saves memory because only one instance is created and used again and again.

Java Design Patterns

Java Singleton Design Pattern

There are various ways to implement singleton design pattern. Here I am discussing two popular ways, Early Instantiation and Lazy Instantiation.

 

A singleton class must have following three things.

Private Static Variable: It contains the instance of the class.

Private Constructor: It prevents further instantiation of class.

Public Static Method: It is a global access point to get the instance of class from outer world.

 

Early Instantiation

In this implementation, the instance is created at the time of class loading. Below example shows how to implement singleton design pattern using early instantiation.

 

SingletonDesginPattern.java

 

Demo.java

 

Output

Java Singleton Design Pattern Using Early Instantiation

 

Lazy Instantiation

In this implementation, the instance is created at request time. Below example shows how to implement singleton design pattern using lazy instantiation.

 

SingletonDesginPattern.java

 

Demo.java

 

Output

Java Singleton Design Pattern Using Lazy Instantiation

 

To make the class thread safe we can create the instance inside synchronized block. It can be done in following way.

 

Comment below if you found any information incorrect or missing in above tutorial.

One comment

  • Lukas Vondracek

    Double check of null reference in thread safe variant doesn’t make sense.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *