单例模式
饿汉式
// 饿汉式单例
public class Hungry {
// 浪费空间
private byte[] data1 = new byte[1024 * 1024];
private byte[] data2 = new byte[1024 * 1024];
private byte[] data3 = new byte[1024 * 1024];
private byte[] data4 = new byte[1024 * 1024];
private Hungry() {
}
private final static Hungry HUNGRY = new Hungry();
public static Hungry getInstance() {
return HUNGRY;
}
}
懒汉式
// 懒汉式单例
public class Lazy {
private static boolean flag = false;
private Lazy() {
synchronized (Lazy.class) {
if (flag == false) {
flag = true;
} else {
throw new RuntimeException("不要使用反射");
}
}
// if (lazy != null) {
// throw new RuntimeException("不要使用反射");
// }
System.out.println(Thread.currentThread().getName());
}
private volatile static Lazy lazy;
// 双重检测锁模式的 懒汉式单例 DCL 懒汉式
public static Lazy getInstance() {
if (lazy == null) {
synchronized (Lazy.class) {
if (lazy == null) {
lazy = new Lazy(); // 不是一个原子性操作
/*
* 1. 分配内存空间
* 2. 执行构造方法 初始化对象
* 3. 把这个对象指向这个空间
* 123
* 132 A
* B 此时Lazy还没有完成构造
* */
}
}
}
return lazy;
}
public static void main(String[] args) throws Exception {
// Lazy lazy1 = Lazy.getInstance();
Constructor<Lazy> declaredConstructor = Lazy.class.getDeclaredConstructor(null);
declaredConstructor.setAccessible(true);
Lazy lazy2 = declaredConstructor.newInstance();
Field flag = Lazy.class.getDeclaredField("flag");
flag.setAccessible(true);
flag.set("flag", false);
Lazy lazy3 = declaredConstructor.newInstance();
// System.out.println(lazy1);
System.out.println(lazy2);
System.out.println(lazy3);
}
// public static void main(String[] args) {
// for (int i = 0; i < 10; i++) {
// new Thread(() -> {
// Lazy.getInstance();
// }).start();
// }
// }
}
静态内部类
// 静态内部类
public class Holder {
private Holder(){
}
public static Holder getInstance() {
return InnerClass.HOLDER;
}
public static class InnerClass{
private static final Holder HOLDER = new Holder();
}
}
因为有反射 所以单例不安全 枚举类
// enum 本事也是一个Class类
public enum EnumSingle {
INSTANCE;
public EnumSingle getInstance() {
return INSTANCE;
}
}
class test{
public static void main(String[] args) throws Exception {
EnumSingle instance1 = EnumSingle.INSTANCE;
Constructor<EnumSingle> declaredConstructor = EnumSingle.class.getDeclaredConstructor(String.class, int.class);
declaredConstructor.setAccessible(true);
EnumSingle instance2 = declaredConstructor.newInstance();
System.out.println(instance1);
System.out.println(instance2);
}
}