java反射技術破壞單例模式

來源:互聯網
上載者:User

 一、 Java中的反射技術可以擷取類的所有方法、成員變數、還能訪問private的構造方法,這樣一來,單例模式中用的私人建構函式被調用就會產生多個執行個體,編寫代碼測試一下。

package test;import java.lang.reflect.Constructor;public class SingetonTest {private static SingetonTest singleton = null;private int s = 0;// 構造方法是私人的private SingetonTest(){}// 同步的擷取執行個體方法public static synchronized SingetonTest getInstance(){// 懶漢模式的單例方法if(null == singleton){singleton = new SingetonTest();}return singleton;}public int getS() {return s;}public void setS(int s) {this.s = s;}/** * @param args */public static void main(String[] args) {try {Constructor con = SingetonTest.class.getDeclaredConstructor();con.setAccessible(true);// 通過反射擷取執行個體SingetonTest singetonTest1 = (SingetonTest)con.newInstance();SingetonTest singetonTest2 = (SingetonTest)con.newInstance();// 常規方法擷取執行個體SingetonTest singetonTest3 = SingetonTest.getInstance();SingetonTest singetonTest4 = SingetonTest.getInstance();// 測試輸出System.out.println("singetonTest1.equals(singetonTest2) :" +  singetonTest1.equals(singetonTest2));System.out.println("singetonTest3.equals(singetonTest4) :" +  singetonTest3.equals(singetonTest4));System.out.println("singetonTest1.equals(singetonTest3) :" +  singetonTest1.equals(singetonTest3));singetonTest1.setS(1);singetonTest2.setS(2);singetonTest3.setS(3);singetonTest4.setS(4);System.out.println("1:" + singetonTest1.getS() + "  2:" + singetonTest2.getS()+ "  3:" + singetonTest3.getS()+ "  4:" + singetonTest4.getS());} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

測試結果:

singetonTest1.equals(singetonTest2) :false
singetonTest3.equals(singetonTest4) :true
singetonTest1.equals(singetonTest3) :false
1:1  2:2  3:4  4:4

通過反射技術產生的兩個執行個體不同,通過常規方法擷取的兩個執行個體相同(即同一個執行個體,單例)。


二、防止反射破壞單例模式,建構函式調用時進行處理,當建構函式第2次被調用時拋出異常。修改構造方法如下:

private static boolean flag = false;// 構造方法是私人的private SingetonTest(){if(flag){flag = !flag;}else{try {throw new Exception("duplicate instance create error!" + SingetonTest.class.getName());} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

三、一些思考

1)單例模式是為了保證一個類只有一個執行個體,整個系統只能有自己建立的一個執行個體。應用在資料庫連接或單個隊列處理等問題。

2)單例模式構造,懶漢模式以時間換空間(用的時候才生產執行個體,每次都判斷);懶漢模式以空間換時間,直接建立執行個體,以後不用判斷直接用。

3)懶漢模式安全執行緒問題,擷取執行個體的方法要加上synchronized進行同步。

4)java的反射技術不要用於執行個體建立,反射主要用於Spring的IOC, Hibernate和白盒測試。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.