Tuesday, 22 September 2015

SingleTon Class in java

The class which has only instance/object  through out the application is known as SingleTon class .


Code of SingleTon class creation
-------------------------------------------------------


//Creation of SingletonClass

public class SingleTonTest {

 private static SingleTonTest instance = null;

 //create an object of SingleObject
 // private static SingleObject instance = new SingleObject();
 //make the constructor private so that this class cannot be instantiated

 private SingleTonTest(){

 }
 //Get the only object available

 public static SingleTonTest getInstance() {

  if(instance == null) {
   instance = new SingleTonTest(); 
  }
  return instance;

 }

 public void showMessage(){
  System.out.println("Hello World!");
 }

 public static void main(String[] args) {

 SingleTonTest object = SingleTonTest.getInstance();
 System.out.println(object);

 SingleTonTest obj = SingleTonTest.getInstance();
 System.out.println(obj);
 //both will print same refrence no.

 }
}

No comments:

Post a Comment