How to make a Class Singleton

Points To Remember

  • To make a class Singleton the class must satisfy the following points
    • No class should be able to make the object of this class.
    • Only one object of this class must me there that is used by all the other classes.
  • The class must have a private constructor so that no class should be able to make object of this class.
  • Class should make a final object of the class itself and return it whenever asked for.
  • Class should have a static method that returns the object of this class.

Demo : Create a Singleton Class

Class : Singleton.java
public class Singleton{

  private String name = "Singleton Object";
  private static final Singleton object = new Singleton();

  private Singleton(){
  }

  public static Singleton getObject(){
    return object;
  }

  public String getName(){
    return name;
  }

}
Class : SingletonTest.java
class SingletonTest{

 public static void main(String args[]){
   Singleton obj = Singleton.getObject();
   System.out.println(obj.getName()); 
 }

}
The output of the following program will be
Singleton Object

No matter how many times you try to get the object of this class, you will always get the same object. Also you can not alter the object since it is final. This type of design pattern can be used to do stuffs like
  • Loading configuration files.
  • Loading credentials
  • Provide constant services to the application.

No comments:

Powered by Blogger.