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);
}
} 

1 thought on “How to create Singleton class in Java?”

  1. Fantastic items from you, man. I’ve be mindful your stuff previous to and you are just too
    great. I actually like what you’ve got right here, certainly like what you
    are saying and the way in which in which you assert it.
    You make it enjoyable and you continue to take care of to keep it smart.

    I cant wait to read much more from you. This is really a
    wonderful site.

Leave a Reply

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