单例模式
时间:2020-04-13 11:58:29
收藏:0
阅读:77
//饿汉式单例
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;
}
}
DCL懒汉式
package com.vogt.single;
?
import javafx.scene.control.Label;
?
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
?
/**
* @author VOGT
* @version V1.0
* @Package com.vogt.single
* @date 2020/4/13 10:34
*/
//懒汉式单例
public class LazyMan {
public static boolean vogt=false;
private LazyMan() {
synchronized (LazyMan.class){
if(vogt==false){
vogt=true;
}else {
throw new RuntimeException("不要试图用反射破坏异常");
}
}
}
?
private volatile static LazyMan lazyMan;
?
public static LazyMan getInstance() {
//双重检测锁模式的懒汉式单例,DCL懒汉式
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, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
//LazyMan instance = LazyMan.getInstance();
Field vogt = LazyMan.class.getDeclaredField("vogt");
vogt.setAccessible(true);
?
Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor(null);
declaredConstructor.setAccessible(true);
LazyMan instance = declaredConstructor.newInstance();
?
vogt.set(instance,false);
?
LazyMan instance2 = declaredConstructor.newInstance();
?
System.out.println(instance);
System.out.println(instance2);
}
?
}
//
// //单线程ok,多线程不行
// public static void main(String[] args) {
// for (int i = 0; i < 10; i++) {
// new Thread(() -> {
// LazyMan.getInstance();
// }).start();
// }
//
//