饿汉式
public class Singleton1 {
private static Singleton1 singleton1 = new Singleton1();
private Singleton1() {
}
public static Singleton1 getInstance() {
return singleton1;
}
}
总结
优点: 线程安全 当类加载的时候对象就被创建了
缺点: 如果项目中有过多的饿汉式 启动会变慢 如果不使用也会被创建 比较占用内存
懒汉式
public class Singleton2 {
private static Singleton2 singleton2;
private Singleton2() { }
public static Singleton2 getSingleton2() {
if (singleton2 == null) {
singleton2 = new Singleton2();
}
return singleton2;
}
}
总结
优点: 在用的时对象才被创建 可以节省内存
缺点: 在多线程情况下 可能会初始化多次 如果加synchronized 又会降低读和写的效率
双重检验锁
public class Singleton3 {
// volatil