单例模式
构造器私有
饿汉式
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) //反射破坏单例,无视私有化
本文深入探讨了单例模式的两种实现方式:饿汉式和懒汉式。饿汉式通过静态初始化实现,而懒汉式则采用双重检测锁确保线程安全。文中还提到了如何通过反射破坏单例模式。
1499

被折叠的 条评论
为什么被折叠?



