饿汉模式
提前创建好了
//饿汉式
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {
//私有构造方法,防止外部实例化
}
public static Singleton getInstance() {
return instance;
}
}
懒汉式
先用先创建
public class Singleton {
private static volatile Singleton instance;
private Singleton(){
//私有构造方法,防止外部实例化
}
public static Singleton getInstance(){
if(instance == null){
synchronized (Singleton.class){
if(instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}