Singleton Design Pattern Java

By | | Updated : 2021-09-28 | Viewed : 88 times

Singleton Design Pattern Java

Singleton is used widely in programming languages such as java. So We will learn here when to use and how to implement singleton class in java.

What is Singleton?

Singleton is a Creational design pattern. Creational design patterns deal with the way of object creation. Singleton allows us to limit object creation to one time. In some of the projects, we may require only one instance for some of the classes in Java. So Singleton is the option to get only one object of particular classes in Java.

Singleton with Eager Initialization

In the Eager initialization, the object will be created after loading the class. Please notice the below given example.

Singleton with Eager Initialization
public class Singleton {

    private static final Singleton instance = new Singleton();

    private Singleton() {
        System.out.println("Singleton object creation...");
    }

    public static Singleton getInstance() {
        return instance;
    }

}

The Eager initialization has one drawback. Even though Singleton objects are not useful in some applications the Eager initialization of Singleton will simply create objects.

Singleton with Static Block Initialization

It is also similar to Eager initialization of the Singleton. The difference is the object is instantiated in a static block.

Singleton with Static Block Initialization
public class Singleton {

    private static final Singleton instance;

    static {
        instance = new Singleton();
    }

    private Singleton() {
        System.out.println("Singleton object creation...");
    }

    public static Singleton getInstance() {
        return instance;
    }
}

Singleton with Lazy Initialization

To overcome the problem of Eager initialization of Singleton The lazy initialization came into the picture. We will look into this how it will be working.

Singleton with Lazy Initialization
public class Singleton {

    private static Singleton instance;

    private Singleton() {
    	System.out.println("Singleton object creation...");
    }

    public static Singleton getInstance() {
        if (instance == null)
            instance = new Singleton();
        return instance;
    }
}

In the Multithreading scenario, the above-given code will fail. It may create more than one object. So the above-given code has to be dealt with for Multithreading. And there are more cases to deal with. We will discuss that in further sections.

Leave A Reply