public class SingletonDemo1 {
private static SingletonDemo1 instance = new SingletonDemo1();
private SingletonDemo1(){
}
public static SingletonDemo1 getInstance(){
return instance;
}
}
public class SingletonDemo2 {
private static SingletonDemo2 instance;
private SingletonDemo2(){
}
public static SingletonDemo2 getInstance(){
if(instance==null){
instance = new SingletonDemo2();
}
return instance;
}
}
public class SingletonDemo3 {
private static SingletonDemo3 instance;
private SingletonDemo3(){
}
public synchronized static SingletonDemo3 getInstance(){
if(instance == null){
instance = new SingletonDemo3();
}
return instance;
}
}
public class SingletonDemo4 {
private volatile static SingletonDemo4 instance;
private SingletonDemo4(){
}
public static SingletonDemo4 getInstance(){
if(instance == null){
synchronized(SingletonDemo4.class){
if(instance==null){
instance = new SingletonDemo4();
}
}
}
return instance;
}
}
public class SingletonDemo5 {
private SingletonDemo5(){
}
private static class SingletonHolder{
private static SingletonDemo5 instance = new SingletonDemo5();
}
public static SingletonDemo5 getInstance(){
return SingletonHolder.instance;
}
}