Java反射結合屬性檔案實現原廠模式__Java

來源:互聯網
上載者:User
通過屬性檔案的形式配置所需要的子類
首先建立一個fruit.properties的資源檔
內容為:
apple=Reflect.Apple
orange=Reflect.Orange

然後編寫主類代碼

//細節:命名規則:類,介面名稱都得大寫;  // 寫完代碼記得格式化,就算是測試代碼,貼出來也是給人看的。不能太水。interface Fruit {    void eat();}class Apple implements Fruit {    public void eat() {        System.out.println("Apple");    }}class Orange implements Fruit {    public void eat() {        System.out.println("Orange");    }}//操作屬性檔案類class Init {    public static Properties getPro() throws IOException {        Properties pro = new Properties();        File f = new File("fruit.properties");        if (f.exists()) {            pro.load(new FileInputStream(f));        } else {            pro.setProperty("apple", "Reflect.Apple");            pro.setProperty("orange", "Reflect.Orange");            pro.store(new FileOutputStream(f), "FRUIT CLASS");        }        return pro;    }}class Factory {    public static Fruit getInstance(String className) {        Fruit f = null;        try {            f = (Fruit) Class.forName(className).newInstance();        } catch (Exception e) {            e.printStackTrace();        }        return f;    }}class Hello {    public static void main(String[] a) throws IOException {        Properties pro = Init.getPro();        Fruit f = Factory.getInstance(pro.getProperty("apple"));        if (f != null) {            f.eat();        }    }}

【運行結果】:Apple

這裡就可以解釋以前看到.properties這種設定檔是幹嘛的啦,

估計大概就是這麼用的,讀取檔案配置,然後就可以修改設定檔的方式來簡單輕鬆的完成一些任務,串連資料的配置也是這樣的咯,大概有個印象,若要詳細瞭解,還得查一番才行。

mongo.properties

memcached.properties

map.properties

default_setting.properties

quartz.properties

在我的這個項目裡面就看到這麼幾個properties類型的檔案,原來這些就是存了一些系統配置啊。

原來如此。

Apple apple = (Apple) f;

咳咳,這個是不行的,人能不強轉成男人,至於為啥就自己猜吧。

編譯時間沒錯,運行時就炸了,這個也是多態的一個常問的問題。就不贅述啦

上面的代碼裡面有個問題。
雖然只是測試代碼,但是裡面的檔案流並沒有正確的關閉,
不知道觀眾的你是否發現啦,我也是回頭再看這個的時候才發現的,或者說是我在知道
如何正確的關閉檔案流之後,再看這個就看到了問題啦。
具體的就看下面這個文章
連結如下:

Java如何正確的使用try catch finally關閉檔案流的總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.