Singleton class in java

Singleton class is a class which ensures that there is only one instance of the class is available throughout the JVM. It is know as Singleton class.

There are three characteristics of a Singleton class
1.Define a private constructor.
2. Define private and static instance
3. Define public and static method for the instance which allow access to instance.


/**
 * singleton class ensures that there is
 * only one instance of the class is available inside the jvm
 */
public class Singleton {

    //characteristic of the singleton class
    //1. private constructor so that no one can create object

    private Singleton() {

    }

    //2. static instance
    private static Singleton instance;

    //3. static method for access

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

Author: Susheel kumar

Leave a Reply

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