How to create Singleton class in Java?

How do you or can you create a Singleton class in Java?

Design patterns are generalized solutions for common development problems in Java. They are provided by experts to solve commonly faced development issues by developers. There are lot of design patterns available in Java, out of which one is Singleton class or object pattern design.

 

What is Singleton class or Singleton object?

Singleton design pattern makes sure that only one instance is created for a class in Java. That means object for a class will be created only once and if we try to initialize one more also we should get the object that is created for the first time, but not a new object.

 

Rules to create Singleton class:

  • Constructor must be private so that other classes cannot call it to create one more object.
  • A private variable of type same class that holds the instance of that class.
  • Public static method that returns the instance of the same class. This is the access point to get the object of Singleton class.

Code:

class SingletonObject {

private static SingletonObject object;
private SingletonObject(){}

public static SingletonObject getInstance(){
if(object == null){
object = new SingletonObject();
}
return object;
}
}

public class SingletonObjectDemo 
{ 
public static void main(String[] args) {
SingletonObject obj = SingletonObject.getInstance();
System.out.println("Singleton object initialized.. "+obj);
}
} 

Leave a Reply

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