懒汉单例模式
package singleInstanceA;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
public class LazyMan {
private static boolean xyz = false;
private LazyMan() {
if (xyz == false) {
xyz = true;
} else {
throw new RuntimeException("不要试图反射破坏异常");
}
}
//必须要volatile,才安全
private volatile static LazyMan lazyMan;
//双重检测锁模式,懒汉式单例 DCL懒汉式
public static LazyMan getInstance() {
if (lazyMan == null) {
synchronized (LazyMan.class) {
if (lazyMan == null) {
lazyMan = new LazyMan();//不是一个原子性操作
/*1分配空间
* 2执行构造方法,初始化对象
* 3把这个对象只想这个空间
*
* 123
* 132 线程A
* B此时,lazyMan还没完成构造
*/
}
;
}
}
return lazyMan;
}
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
/* for (int i = 1; i <= 10; i++) {
new Thread(() -> {
LazyMan.getInstance();
}).start();
}*/
//LazyMan instance = LazyMan.getInstance();
Field xyz = LazyMan.class.getDeclaredField("xyz");
xyz.setAccessible(true);
Constructor<LazyMan> constructor = LazyMan.class.getDeclaredConstructor(null);
constructor.setAccessible(true);
LazyMan L1 = constructor.newInstance();
xyz.set(L1,false);
LazyMan L2 = constructor.newInstance();
//System.out.println(instance);
System.out.println(L1);
System.out.println(L2);
}
}
饿汉单例模式
package singleInstanceA;
/**
* 单例模式
* 饿汉单例模式
* 1,某个类只有一个实例
* 2,实例必须该类自行创建
* 3,必须自行想整个系统提供实例
*
* @author liu
*/
public class Hungry {
//弊端:可能会浪费空间
private byte[] a = new byte[1024];
//构造方法私有,外部不能new
private Hungry() {
}
//内部new的对象也私有
private static Hungry hungry= new Hungry();
//只留一个获取对象的方法
public static Hungry getInstance() {
return hungry;
}
}
静态内部类
package singleInstanceA;
public class Holder {
private Holder() {
}
public static Holder getInstance() {
return InnerClass.HOLDER;
}
public static class InnerClass {
public static final Holder HOLDER = new Holder();
}
}