
如何才能搞懂Java設(shè)計模式?從最重要的單例模式開始吧!
單例模式
餓漢式
// 餓漢式單例
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];
加入Java開發(fā)交流君樣:484138291一起吹水聊天
private Hungry() {
}
private final static Hungry HUNGRY = new Hungry();
public static Hungry getInstance() {
return HUNGRY;
}
}
懶漢式
// 懶漢式單例
public class Lazy {
private static boolean flag = false;
private Lazy() {
synchronized (Lazy.class) {
if (flag == false) {
flag = true;
} else {
throw new RuntimeException("不要使用反射");
}
}
// if (lazy != null) {
// throw new RuntimeException("不要使用反射");
// }加入Java開發(fā)交流君樣:484138291一起吹水聊天
System.out.println(Thread.currentThread().getName());
}
private volatile static Lazy lazy;
// 雙重檢測鎖模式的 懶漢式單例 DCL 懶漢式
public static Lazy getInstance() {
if (lazy == null) {
synchronized (Lazy.class) {
if (lazy == null) {
lazy = new Lazy(); // 不是一個原子性操作
/*
* 1\. 分配內(nèi)存空間
* 2\. 執(zhí)行構(gòu)造方法 初始化對象
* 3\. 把這個對象指向這個空間
* 123
* 132 A
* B 此時Lazy還沒有完成構(gòu)造
* */
}
}
}
return lazy;
}
public static void main(String[] args) throws Exception {
// Lazy lazy1 = Lazy.getInstance();
Constructor<Lazy> declaredConstructor = Lazy.class.getDeclaredConstructor(null);
declaredConstructor.setAccessible(true);
Lazy lazy2 = declaredConstructor.newInstance();
Field flag = Lazy.class.getDeclaredField("flag");
flag.setAccessible(true);
flag.set("flag", false);
Lazy lazy3 = declaredConstructor.newInstance();
// System.out.println(lazy1);
System.out.println(lazy2);
System.out.println(lazy3);
}
// public static void main(String[] args) {
// for (int i = 0; i < 10; i++) {
// new Thread(() -> {
// Lazy.getInstance();
// }).start();
// }
// }
}
靜態(tài)內(nèi)部類
// 靜態(tài)內(nèi)部類
public class Holder {
private Holder(){
}
public static Holder getInstance() {
return InnerClass.HOLDER;
}
public static class InnerClass{
private static final Holder HOLDER = new Holder();
}
}
因為有反射 所以單例不安全 枚舉類
// enum 本事也是一個Class類
public enum EnumSingle {
INSTANCE;
public EnumSingle getInstance() {
return INSTANCE;
}
}
class test{
public static void main(String[] args) throws Exception {
EnumSingle instance1 = EnumSingle.INSTANCE;
Constructor<EnumSingle> declaredConstructor = EnumSingle.class.getDeclaredConstructor(String.class, int.class);
declaredConstructor.setAccessible(true);
EnumSingle instance2 = declaredConstructor.newInstance();
System.out.println(instance1);
System.out.println(instance2);
}
}
分類: Java設(shè)計模式