How To Create Singleton Class in Java

Create a basic singleton class template in Java

Table of Contents

Design patterns Overview

Design patterns are basically solutions to programming problems that developers normally encounter during software development. Design patterns were first documented by four authors known as the Gang of Four (GoF).

Design patterns are broadly classified into creational, structural, and behavioral patterns. Creational patterns aid in object creation, structural patterns help to alter the structure of an object while behavioral patterns mostly have to do with algorithms.

Introduction to Singleton Pattern

Singleton is a creational design pattern; it helps in creating an object of a class. The Singleton pattern ensures that there is only one instance of a class. It is generally used for a class that consumes a lot of memory or one that uses expensive resources. Singleton ensures that there is only one instance of the class, thus saving on memory and other resources. The singleton pattern is mostly used for database connections, caching, logging, and other programming situations that mandate having a single object of a class.

Singleton Pattern Implementation

There are three main ways in which the singleton pattern can be implemented. All the approaches make use of a static instance, a private constructor, and a public getter method.

Eager Initialization

In this approach, the Singleton instance is created at the time the class is loaded. The following code demonstrates creating a Singleton class using this approach:

class MySingleton {
   private static MySingleton mySingleton = new MySingleton();
   private MySingleton() {
   }
   public static MySingleton getMySingleton() {
      return mySingleton;
   }
}

This code specifies a class called MySingleton. It has a private static instance field called mySingleton that is initialized at the time of creation. It also has a private constructor. Finally, there is a public getter method called getMySingleton(). This method returns the mySingleton instance. 

So, in this approach, the singleton instance is created much before it is used. If the singleton is a heavy class using a lot of resources, then this approach is not appropriate.

Lazy Initialization

In this approach, the Singleton instance is created when it is first requested. The following code demonstrates this:

public class MySingleton {
private static MySingleton mySingleton;
   private MySingleton() {
   }
   public static MySingleton getMySingleton() {
      if (mySingleton == null) {
         mySingleton = new MySingleton();
      }
      return mySingleton;
   }
}

This approach is similar to the eager initialization approach in that it has a private static instance field, a private constructor and a public getter method. The only difference is that the singleton instance is not created at start-up. Instead, the getMySingleton() method checks if an instance of the singleton class exists. If so, it just returns it. If an instance does not exist, it creates it via the private constructor.

So, in this approach the singleton instance is created when it is first requested. This is the preferred approach for singleton classes that use a lot of resources.

Static block Initialization

In this approach, the singleton instance is created within a static block. The following code demonstrates this:

class MySingleton {
   private static MySingleton mySingleton;
   private MySingleton() {
   }
   
   static {
      mySingleton = new MySingleton();
   }
   public static MySingleton getMySingleton() {
      return mySingleton;
   }
   
}

Just like the previous approaches, this code defines a private static instance, a private constructor and a public getter method. In addition, this code also defines a static block. The singleton instance mySingleton is created in this static block. Since a static block is executed only once this ensures that there is only one instance of the singleton. Since the static block is executed when the class is loaded, the singleton instance is created at start-up just like it is done in the eager initialization approach.

The advantage of this approach over the eager initialization approach is that, exception handling code can be added in the static block. So, if there is an error while creating the singleton instance, an appropriate exception can be thrown.

Advantages of Singleton

There are several advantages of using a singleton class.  It helps it saving on memory and other resources by ensuring that there is only one instance of the class. It provides global access to the singleton instance. It gives a class control over the instantiation process.

Disadvantages of Singleton

The Singleton pattern has some disadvantages too. For one, singleton objects are often used as global variables which is against object-oriented principles like encapsulation. Secondly, singletons make unit testing difficult. A class that uses a singleton object cannot be tested by itself.

Conclusion

So, in this article, we understood the basics of the singleton design pattern. We also saw some of the ways in which you can implement the singleton pattern in Java. Finally, we understood some of the advantages and disadvantages of the singleton pattern.

Tushar Sharma
Tushar Sharmahttps://www.automationdojos.com
Hi! This is Tushar, the author of 'Automation Dojos'. A passionate IT professional with a big appetite for learning, I enjoy technical content creation and curation. Hope you are having a good time! Don't forget to subscribe and stay in touch. Wishing you happy learning!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Recent Posts

RELATED POSTS

Create Basic Hibernate Program

Hibernate is an ORM framework that helps in accessing database tables from Java code. It is an object-oriented way of accessing database tables and...

How To Sort List in Java

Introduction A List is an interface in the Java collection framework. It can be used to store objects. Programmers often encounter scenarios where they need...

Java Tutorial #4 – Control Statements

Introduction Control statements are used to change the flow of execution based on changes to certain variables in the code. One of the types of...

Â

RECENT 'HOW-TO'

How To Install Oh-My-Posh On Windows PowerShell

Oh-My-Posh is a powerful custom prompt engine for any shell that has the ability to adjust the prompt string with a function or variable. It does not...

SIMILAR ON CODEX

FEATURED PROJECTS

Windows JDK Manager (win-jdk-Manager)

ADjo LABS PROJECT : Simple and lightweight desktop utility with Interactive cmd Interface for easy view, re-point and switching between JAVA versions on windows. Demonstrating the capability...

MORE IN THIS CATEGORY

Convert List to Array Using For-Loop

The simplest way to convert a List to an array is to use a for-loop. The following code snippet demonstrates this method. First, the code...

How To Sort List in Java

Introduction A List is an interface in the Java collection framework. It can be used to store objects. Programmers often encounter scenarios where they need...

How To Concatenate Strings in Java

Introduction In Java, a String is a sequence of characters. There are often programming situations where you will need to concatenate Strings. There are several...

CHECKOUT TUTORIALS

Getting Started with Apache JMeter

1. Introduction As a developer, you may have tested the functionality of your code hundreds of times during development. This is known as functional testing....
- Advertisement -spot_img