Implement Singleton Pattern with private constructor - Java Object Oriented Design

Java examples for Object Oriented Design:Static

Introduction

A singleton class is a class that you can use to create only one instance.

Demo Code

class SingletonClass {
  private static SingletonClass instance;

  private SingletonClass() {
  }/*from  ww w . j a v a 2 s. c o  m*/

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

public class Main {
  public static void main(String[] args) {
    SingletonClass s1 = SingletonClass.getInstance();
    SingletonClass s2 = SingletonClass.getInstance();
    if (s1 == s2)
      System.out.println("The objects are the same");
    else
      System.out.println("The objects are not the same");

  }

}

Related Tutorials