黑客:程式碼揭示特斯拉 Beta 版 FSD 正在中國進行測試
阿新 • • 發佈:2021-09-07
單例模式之餓漢式模式
- 餓漢式模式來歷 直接例項化猶如餓漢子儘快想把飯吃完故稱為餓漢式
public class Hungry{
public static final Hungry hungry = new Hungry();
private Hungry(){}
private static final Hungry getInstance{
return hungry;
}
}
單例模式之懶漢式模式
- 懶漢式模式來歷 延遲例項化,懶載入故稱為懶漢式
public class LayMan{ public static volatile LayMan layMan = null; private LayMan(){} //DCL雙重檢測 private static LayMan getInstance{ if(layMan!=null){ synchronized (layMan.class){ if(layMan != null){ layMan = new LayMan(); //不是原子的操作,需要在 private volatile static LayMan1 layMan1 = null; } } } return layMan; } }
單例模式之靜態類實現模式
- 靜態類單例模式
package com.gof23.single1; import com.gof23.single.StaticClass; public class StaticClass1 { private StaticClass1(){ } private static class InnerClass{ private static StaticClass1 staticClass1 = new StaticClass1(); } private static StaticClass1 getInstance(){ return InnerClass.staticClass1; } public static void main(String[] args) { StaticClass1 s1 = StaticClass1.getInstance(); StaticClass1 s2 = StaticClass1.getInstance(); System.out.println(s1 == s2); } }
單例模式之列舉類實現模式
- 列舉單例模式
package com.gof23.single; import sun.security.jca.GetInstance; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public enum EnumInstance { INSTANCE; private static EnumInstance getInstance(){ return INSTANCE; } public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { EnumInstance instance1 = EnumInstance.getInstance(); EnumInstance instance2 = EnumInstance.getInstance(); System.out.println(instance1); System.out.println(instance2); Constructor constructor = instance1.getClass().getDeclaredConstructor(); constructor.setAccessible(true); EnumInstance instance3 = (EnumInstance) constructor.newInstance(); System.out.println(instance3); } }
小結: 1. 單例模式都會反射安全性問題,通過反射構造器newInstance會破壞單例模式
2. enum列舉類單例模式不存在反射安全性問題