Computers

Creating a Singleton in Java

Here's a simple way to create a Singleton class

 

SingletonClass.java

public class SingletonClass {
  private static SingletonClass instance = new SingletonClass();

  private SingletonClass() {
    try {
      // Some singleton stuff like loading properties     } catch(Exception e) {
      throw new RuntimeException(e);
    }
  }

  public static SingletonClass getInstance() {
    return instance;
  }

  public Object getXXX() {
    // Some getters   }

  public void setXXX(Object object) {
    // Some setters   }
}

Another approach is

SingletonClass.java

public class SingletonClass {
  private static SingletonClass instance = null;

  private SingletonClass() {
    try {
      // Some singleton stuff like loading properties     } catch(Exception e) {
      throw new RuntimeException(e);
    }
  }

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

  public Object getXXX() {
    // Some getters   }

  public void setXXX(Object object) {
    // Some setters   }
}