饿汉式,简单安全
public class Singleton{
private Singleton(){}
private static Singleton instance = new Singleton();
public static Singleton getInstance(){
return instance;
}
}
懒汉式
public class Singleton{
private Singleton(){}
private static Singleton instance;
public static synchronized Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
双重检查,加volatile,在线程间通知变量的变化
public class Singleton{
private Singleton(){}
private static volatile Singleton instance;
public static synchronized Singleton getInstance(){
if(instance == null){
synchronized(Singleton.class){
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
一个对象new的过程需要两步:
1.preparation 准备
2.initilization 初始化
最后一点:静态内部类实现单例