单例模式
构造器私有
饿汉式
package com.singleMode;
public class Hungry {
private byte[] bytes1 = new byte[1024*1024];
private byte[] bytes2 = new byte[1024*1024];
private byte[] bytes3 = new byte[1024*1024];
private byte[] bytes4 = new byte[1024*1024];
private byte[] bytes5 = new byte[1024*1024];
private Hungry(){
}
private static final Hungry HUNGRY = new Hungry();
public static Hungry getInstance(){
return HUNGRY;
}
}
DLC懒汉式
package com.singleMode;
public class LazyMan {
private LazyMan(){
}
private volatile static LazyMan lazyMan; //禁止指令重排
public LazyMan getInstance(){
if (lazyMan==null){ //双重检测锁模式
synchronized (LazyMan.class){
if (lazyMan==null){
LazyMan lazyMan = new LazyMan(); //不是原子性操作
}
}
}
return lazyMan;
}
}
declareConstructor.setAccessible(ture) //反射破坏单例,无视私有化