单例模式
懒汉式
public class LHan {
private static LHan instance;
private LHan() {} //必要的一步,构造器私有化
public static LHan getInstance() {
if (instance == null) {
instance = new LHan();
}
return instance;
}
}
饿汉式
public class EHan {
private static EHan instance= new EHan();
private EHan(){}
public static EHan getInstance(){
return instance;
}
}//好处是没有线程安全的问题,坏处是浪费内存空间。
双检锁模式
public class DoubleCheckSingletonle {
private volatile static DoubleCheckSingletonle instance; // 禁止指令重排
private DoubleCheckSingletonle() {}
public static DoubleCheckSingletonle getInstance() {
if (instance == null) {
synchronized (DoubleCheckSingletonle.class) {
if (instance == null) {
instance = new DoubleCheckSingletonle(); //分为三步 1 分配内存空间 2初始化对象 3将对象指向内存空间
//编译器优化后 可能将 2和3 进行反序 导致 第二个线程进来时 可能拿到 未分配好点对象
}
}
}
return instance;
}
}
静态内部类
public class StaticInnerClassSingletonle {
private static StaticInnerClassSingletonle instance;
private StaticInnerClassSingletonle() {}
private static StaticInnerClassSingletonle getInstance() {
return SingletonleHolder.INSTANCE;
}
// 静态内部类
private static class SingletonleHolder {
private static final StaticInnerClassSingletonle INSTANCE = new StaticInnerClassSingletonle();
}
}
枚举
public enum Singleton {
INSTANCE;
public void anyMethod(){}
}