Program to demonstrate how to make a class singleton in Java using Singleton Design Pattern.
package com.hubberspot.designpattern.creational.singleton;
//Steps to make a class Singleton in nature :-
// 1. Create a class by name say SingletonClass
public class SingletonClass {
// 2. Create a private default constructor of the
// class created above in step 1.
private SingletonClass() {
}
// 3. Create a private static variable of type class
// created in step 1 itself. It should be private,
// static and gets reference to instance of class itself.
private static SingletonClass SINGLETON_INSTANCE =
new SingletonClass();
// 4. Create a static accessor method which always
// return us back the same instance created in
// step 3. The name of the method could be
// according to good naming convention as :
// getInstance()
public static SingletonClass getInstance() {
return SINGLETON_INSTANCE;
}
// 5. There should not be any method or constructor
// which creates another object of SingletonClass.
}