饿汉模式
提前创建好了
//饿汉式
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;
}
}
标签:Singleton,--,private,class,instance,static,模式,单例,public
From: https://blog.csdn.net/m0_68935893/article/details/141162128