Tag Archives: Java

Singleton : Restrict instantiation of a class to one object

In order to achieve this, first thing which we need to do is make the class’s constructor private, which in turn will not allow any other class (outside) to create an abject of that class directly using the constructor. After this we can just define a getInstance method, which does the required two things:
1. Check how many objects of the class have been created.
2. Depending on (1) return an instance of the class.

Here is the code :

/*
  @file : test.java
*/

class Singleton {
  private static int counter=0;

  private Singleton() { //private constructor
    System.out.println("Object instantiated!");
  }

  static Singleton getInstance() {
    if (counter < 1 ) { // to allow only 1 object creation.
      Singleton inst = new Singleton();
      counter ++;
      return inst;
    }

    System.out.println("Can't instantiate further ..");
    return null;
  }
}

public class test {
  public static void main(String str[]){
    Singleton ins1 = Singleton.getInstance();
    Singleton ins2 = Singleton.getInstance();
    Singleton ins3 = Singleton.getInstance();
  }
}

Output :

$ java test
Object instantiated!
Can't instantiate further ..
Can't instantiate further ..