懒汉式 先判断是否已经实例化,如果没有则实例化,有则直接返回.
public class Single {
private static Single single=null;
private Single(){}
public static synchronized Single getSingleton (){
if(single!=null){
return new Single();
}
return single;
}
}
饿汉式 一开始就实例化
public class Singleton2 {
private final static Singleton2 singleton2=new Singleton2();
private Singleton2(){
}
public static Singleton2 getSingleton2(){
return singleton2;
}
}
优化版懒汉式(线程安全的懒汉式,性能比懒汉式好)
public class Single {
private static Single single=null;
private Single(){}
public static Single getSingleton (){
if(single!=null){
synchronized(Single.class){
if(single!=null){
return new Single();
}
}
}
return single;
}
}