懒汉式
线程不安全
public class Singleton {
private Singleton() {};
private static Singleton instance = null;
public static Singleton getInstace() {
if(instance == null)
instance = new Singleton;
return instance;
}
}
线程安全(双重检查锁)
public class Singleton {
private Singleton() {};
private static Singleton instance = null;
public static Singleton getInstace() {
if(instance == null)
synchnorized(Singleton.class);
if(instace == null)
instance = new Singleton;
return instance;
}
}
饿汉式(线程安全)
public class Singleton2 {
private Singleton() {};
private static final Singleton instance = new Singleton2();//类加载便完成初始化,不存在多个线程创建多个实例
public Singleton getInstance() {
return instance;
}
}
缺点:即使单例没有被用到也会被创建,浪费内存