单例模式

p确保创建全局唯一对象


ackage com.zou.single;
//饿汉式单例
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() {
}
//保证new出来的对象是唯一的,一上来就把对象加载
private final static Hungry HUNGRY=new Hungry();
//给他一个抛出对外的方法
public static Hungry getInstance(){
return HUNGRY;
}
}


package com.zou.single;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

//懒汉式
public class LazyMan {
private static boolean deng=false;
//构造器私有
private LazyMan() {//防止反射利用无参构造器
synchronized (LazyMan.class){
if (deng==false){
deng=true;
}else {
throw new RuntimeException("不要试图用反射");
}

}
System.out.println(Thread.currentThread().getName()+"ok");//确保线程启动
}
//不是一上来就加载对象
private volatile static LazyMan lazyMan;//volatile避免指令重排
public static LazyMan getInstance() {
//需要双层检测锁,DCL懒汉式单例
if (lazyMan == null) {
synchronized (LazyMan.class) {//确保只有一个
if (lazyMan == null) {//如果为空再去创建
lazyMan = new LazyMan();//不是原子性操作,指令重排
}
}

}
return lazyMan;
}
//反射
public static void main(String[] args) throws Exception {
//LazyMan instance=LazyMan.getInstance();
Field deng =LazyMan.class.getDeclaredField("deng");
deng.setAccessible(true);
Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor(null);//空参构造器
declaredConstructor.setAccessible(true);//破坏私有
LazyMan instance = declaredConstructor.newInstance();//若两个都是反射创建--红路灯标志
deng.set(instance,false);
LazyMan instance2 = declaredConstructor.newInstance();
System.out.println(instance2);
System.out.println(instance);
}
}



package com.zou.single;
//静态内部类
public class Holder {
//构造器私有

private Holder() {

}
public static Holder getInstance() {
return InnerClass.HOLDER;//不安全,反射破解
}
public static class InnerClass{
private static final Holder HOLDER =new Holder();//在内部类调外部类
}
}




package com.zou.single;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

//枚举 --他也是一个类,反射不能破坏枚举
public enum EnumSingle {
INSTANCE;
public EnumSingle getInstance(){
return INSTANCE;
}
}
class test{
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
EnumSingle instance=EnumSingle.INSTANCE;
Constructor<EnumSingle> declaredConstructor = EnumSingle.class.getDeclaredConstructor(String.class,int.class);//空参构造器
EnumSingle enumSingle = declaredConstructor.newInstance();
System.out.println(instance);
System.out.println(enumSingle);
}
}
上一篇:[Leetcode 111]二叉树的最短深度 BFS/DFS


下一篇:LeetCode 994. 腐烂的橘子--BFS搜索