懒汉式(线程安全)
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;
}
}
饿汉式
public class Singleton {
private static Singleton singleton = null;
static {
singleton = new Singleton();
}
private Singleton(){}
private static Singleton getInstance(){
return singleton;
}
}