×

Singleton Design Pattern in Java

In the singleton pattern, a class that only has one instance and offers a universal point of access is taken into consideration.

It can also be defined in another way, a class must make sure that only one instance is produced and that only one object can be utilized by all other classes.

This particular design pattern falls under the category of a creational pattern because it provides one of the simplest ways to make an object.

Use of Singleton Pattern Design

This pattern design is mainly used to create the object such that only one object is created for a class and this class provides the technique of retrieving the class's unique object, removing the need to create it first.

This singleton pattern is also used in applications that involve datasets and multiple threads frequently

It is involved in the configuration files or specifications, threaded pools, caching, and logging, among many other things.

Implementation of Singleton Pattern Design

It implemented in three steps, such as:

  1. Make a Singleton Class first.
  2. Take the sole instance of the singleton class's object.
  3. Check the results.

There will be just one object class created. The static instance of the SingleObject class as well as the private function Object() [native code] are both available.

The SingleObject class offers a static method to return its static instance to the outside world.Our demo class, SingletonPatternDemo, will use the SingleObject class to obtain a SingleObject object.

Types of singleton pattern design

There are two types of singleton pattern design

  • Early instantiation
    • Using static block
  • Lazy instantiation
    • Thread Safe Singleton
    • Lazy initialization with Double check locking
    • Bill Pugh Singleton Implementation

Early instantiation

In short, it is defined as the process of instance creation when loading or at a load time.

This is considered to be the simplest method for developing a singleton time up ahead. An object of that class is created when the JVM loads the class into memory.It is accomplished by directly assigning an instance's reference.

When a computer will always use an instance of this class or when constructing an instance didn't accept up a lot of time or resources, it can be used.

Example

// Early Initialization
public class Early
{
  private static final Early instance = new Early();
  private Early()
{
//private constructor
}
 public static EalrygetInstance()
    {
        return instance;
    }
}

Using static block

This static block is the sub-part of the early instantiation or initialization.

The main difference is that objects are again created in static blocks so that we may access them immediately after they are created and handle exceptionsSimilarly, when a class is loaded, an object is produced.

// using static block
import java.io.*;
public class Sb
{
  public static Sb instance;
 private Sb()
  {
    // private constructor
  }
static
  {
    instance = new Sb();
  }
}

Advantages of Early instantiation

  • extremely easy to use.
  • certainly wastes resources. because whether or not it is necessary, a class instance is always produced.
  • Instance creation that is not necessary wastes CPU time as well.
  • There is no way to handle exceptions.

Lazy instantiation

In short, it is defined as the process of instance creation when needed

Going into it, here the object is created only when it is necessary.It is required to implement the method called asgetInstance(), which returns the instance. There is a null check that, if true, creates the object; else, it returns the one that has already been constructed.

The constructor is made final to ensure that the class cannot be created in any other way. Because objects are generated within methods, it is guaranteed that they won't be produced until and unless they are needed. To prevent direct access, instances are kept private.

The source wastage is prevented by this initialization method

Example

// With Lazy initialization
public class Li
{
  private static GFG instance;
  private Li()
  {
    // private constructor
  }


  public static Li getInstance()
  {
    if (instance == null)
    {
      // if instance is null, initialize
      instance = new Li();
    }
    return instance;
  }
}

Thread-safe singleton

Creating a thread-safe singleton allows for the preservation of singleton properties even in multithreaded environments. A singleton class is made thread-safe by synchronizing the getInstance() method so that multiple threads cannot access it simultaneously.

Example

public class Thread
{
 private static Thread instance;
 private Thread()
  {
    // private constructor
  }
  synchronized public static Thread getInstance()
  {
    if (instance == null)
    {
      instance = new Thread();
    }
    return instance;
  }
}

Advantages of Lazy instantiation

  • Only when it is necessary is an object created.
  • It is also feasible for methods to handle exceptions.
  • Each time, the null condition must be verified.
  • No direct access is possible to instance.

Real-time Example for single pattern design in java

class Singleton
 {
private int n = 20;
private Singleton() 
{
}
private static class Helper {
private static final SingletonuniqueInstance = new Singleton();
}
public static Singleton getInstance() {
return Helper.uniqueInstance;
}


public int getNum() {
return n;
}


public void setNum(int n) {
this.n = n;
}


}


public class SingletonDemo {
public static void main(String args[]) {
Singleton singleInstance = Singleton.getInstance(); // first instance of the class
singleInstance.setNum(25);
Singleton secondInstance = Singleton.getInstance(); // second instance of the class
System.out.println(secondInstance.getNum()); // trying to get the class variable using getter method
}
}

Related Topics

Print Pencil Shape Pattern in Java

Another pattern made from asterisk symbols that use loops and other logical concepts is the pencil pattern. It is usually requested to draw a pattern using a program. To write the...

6 minutes read.

Model Class in Java

In this section, we will be acknowledged about the model class in Java, its purpose and its uses. Also, we will learn how is this created and leveraged in java. Model...

4 minutes read.

How to Iterate List in Java?

List is a Collection foundation interface in Java. It enables us to keep the collection of objects in order. The four classes that make up the List interface implementation are...

3 minutes read.

Tower of Hanoi Program in Java

Tower of Hanoi Program in Java The Tower of Hanoi program in Java is written to solve a mathematical puzzle, called Tower of Hanoi, where we have three poles and n...

4 minutes read.

Java Boyer Moore

A string searching or matching technique called the Boyer-Moore algorithm was created in 1977 by Robert S. Boyer and J. Strother Moore. It is the most popular and effective string-matching...

9 minutes read.

Java Math sinh() Method

The sinh() method of Java Math class returns the hyperbolic sine of the specified double value. Syntax: public static double sinh(double x) Parameters: The parameter ‘a’ represents the number whose hyperbolic sine is to...

2 minutes read.

Java Try Keyword

The try block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java try block has...

3 minutes read.

Shallow copy in Java

Java's most important task is making a copy or clone of an object. In this part, we'll talk about shallow copies in Java and how to make them of Java...

4 minutes read.

Java Enum

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four iterators named Club, Diamond,...

3 minutes read.

Virtual Function in Java

In the Operated Oriented Programming language, a virtual function or virtual method is a collection of functions that overrides the functionality of a function in an inheriting class with the same...

4 minutes read.

How to handle NullPointerException in Java

Introduction: Throwable class is the super or root class of the java exception hierarchy which contains two sub-classes. The classes’ are- ExceptionError Exception: If you are doing any wrong things in a...

3 minutes read.

Difference between JDK, JRE and JVM In Java

In the Java ecosystem, three primary components are often mentioned: JDK, JRE, and JVM. Here’s a breakdown of each: Java Development Kit (JDK) The Java Development Kit (JDK) is a comprehensive software...

2 minutes read.

MOOD Factors to Assess a Java Program

In this tutorial, we will comprehendthe meaning of mood factors in Java. For the development of any software system,the quality of anapplication is important. It is more important to maintain large-scale...

4 minutes read.

Hierarchy of operators in Java

Operators are the most frequently used terminology in any area of programming, and it helps in various approaches to efficiently solve daily life problems by computer programming. The simple addition of...

4 minutes read.

Java Thread class

Thread class The thread represents a part of the process. Every process can have multiple associated threads in which every thread may execute the same or different job. By default, each thread assigns...

16 minutes read.

Multithreading Program in Java

Multithreading Program in Java: Before discussing multithreading, it is important to discuss threads. Threads are the most fundamental part of a process. A process can have one or more threads....

4 minutes read.

Zigzag Array in Java

In this tutorial, we discuss, what is zigzag array and its example. Even we will create the java program. In this program, we convert the simple array into a zigzag...

4 minutes read.

Java Try-Catch Block

Java Try Block The handling of the exceptions in a block of code is done with the help of java try block. It throws the code that is enclosed in a...

3 minutes read.

Java Polymorphism

The process of representing one form in multiple forms is known as Polymorphism. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means...

5 minutes read.

Print Matrix Diagonally in Java

The aim is to print the elements of a matrix of size n*n in some kind of a diagonal pattern. Input : mat[3][3] = {{1, 2, 3},                      {4, 5, 6},                      {7,...

3 minutes read.