优点:延迟加载
缺点:不加同步的懒汉式是线程不安全的,加了synchronized之后就变成线程安全的了
public class Singleton {
private static Singleton singleton = null;
private Singleton(){
}
public static synchronized Singleton getInstance(){
if(singleton == null){
singleton = new Singleton();
}
return singleton;
}
}
优点:线程安全
缺点:浪费内存空间
实例应用:java.lang.Runtime
public class Singleton {
private static final Singleton singleton = new Singleton();
private Singleton(){
}
public static Singleton getInstance(){
return singleton ;
}
}
特点:性能又保证线程安全
public class Singleton{
private static Singleton singleton;
private Singleton(){
}
public static Singleton getInstance(){
if(singleton == null){
synchronized(Singleton.class){
if(singleton == null){
singleton = new Singleton();
}
}
}
return singleton;
}
}