Wednesday 25 November 2015

How to Make Singleton Class In Java

package com.javaproficiency;

public class SingletonDemo {

static SingletonDemo obj;
private  SingletonDemo(){
}

public static SingletonDemo getInstance(){
 if(obj!=null){
  return  obj;
 }
 else{
  obj=new SingletonDemo();
 return obj;
 }
}

public static void main(String[] args) {

SingletonDemo obj1 = SingletonDemo.getInstance();
SingletonDemo obj2 =  SingletonDemo.getInstance();

if( obj1 == obj2 ){
System.out.println(" singleton object ");
}else{
System.out.println(" not singleton object ");
}

System.out.println(obj1==obj2);
}


}

Output:

 singleton object
 true

1 comment:

  1. public class SingletonDemo {
    private SingletonDemo() {
    }

    public static SingletonDemo getInstance() {
    return Wrapper.instance;
    }

    private static class Wrapper {
    private static SingletonDemo instance = new SingletonDemo();
    }

    ReplyDelete