JAVA_单例模式
一定要掌握并且会白板默写的三种单例模式实现。
饿汉式:
public class Singleton1 {
// 必须private修饰
private static final Singleton1 SINGLETON = new Singleton1();
// 无参构造必须private
private Singleton1(){}
// 获取单例的方法,必须public且是静态方法
public static Singleton1 getInstance(){
return SINGLETON;
}
}
懒汉式(双重检查):
public class Singleton2 {
// 必须是volatile修饰,保障单例共享变量的有序性和可见性
private static volatile Singleton2 singleton2 = null;
private Singleton2(){}
public static Singleton2 getInstance(){
if(singleton2 == null){
synchronized (Singleton2.class){
if(singleton2 == null){
// 这行代码,涉及到的执行操作分成多个步骤,必须保障机器指令的有序性,避免其它线程判断null时出现误判
singleton2 = new Singleton2();
}
}
}
return singleton2;
}
}
静态内部类:
public class Singleton3 {
private Singleton3(){}
private static class SingletonHolder{
private static final Singleton3 SINGLETON = new Singleton3();
}
public static Singleton3 getInstance(){
return SingletonHolder.SINGLETON;
}
}