可能总结的会有问题,我会一点点完善的...
结论:建议使用第 4 种饿汉方式。如果明确要实现懒加载效果时,使用第 5 种静态内部类方式。如果涉及到反序列化创建对象时,可以使用第 6 种枚举方式。
1 懒汉式,线程不安全
public class Singleton {
private static Singleton instance=null;
public static Singleton getInstance(){
if(instance==null){
instance=new Singleton();
}
return instance;
}
private Singleton(){}
}
2 懒汉式,线程安全
public class Singleton {
private static Singleton instance=null;
public static synchronized Singleton getInstance(){
if(instance==null){
instance=new Singleton();
}
return instance;
}
private Singleton(){}
}
3 双重检查锁,懒汉式,线程安全
public class Singleton {
private volatile static Singleton instance=null;
public static Singleton getInstance(){
if(instance==null){
synchronized(Singleton.class){
if(instance==null){
instance=new Singleton();
}
}
}
return instance;
}
private Singleton(){}
}
4 饿汉式,线程安全
public class Singleton {
private static Singleton instance=new Singleton();
public static Singleton getInstance(){
return instance;
}
private Singleton(){}
}
5 静态内部类,懒汉式,线程安全
public class Singleton {
private static class SingletonHolder{
private final static Singleton instance=new Singleton();
}
public static Singleton getInstance(){
return SingletonHolder.instance;
}
private Singleton(){}
}
6 枚举类,懒汉式,线程安全
public enum SingletonEnum{
INSTANCE;
}