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
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
public class SingletonDemo {
ReplyDeleteprivate SingletonDemo() {
}
public static SingletonDemo getInstance() {
return Wrapper.instance;
}
private static class Wrapper {
private static SingletonDemo instance = new SingletonDemo();
}