通過反射優化工廠模式

1.工廠模式

工廠模式是我們最常用的實例化對象模式了,是用工廠方法代替new操作的一種模式。著名的Jive論壇 ,就大量使用了工廠模式,工廠模式在Java程序系統可以說是隨處可見。因爲工廠模式就相當於創建實例對象的new,我們經常要根據類Class生成實例對象,如A a=newA() 工廠模式也是用來創建實例對象的,所以以後new時就要多個心眼,是否可以考慮使用工廠模式,雖然這樣做,可能多做一些工作,但會給你係統帶來更大的可擴展性和儘量少的修改量。

具體內容見另一篇博客

2.不足

當增加一個子類的時候需要修改工廠類,這樣很麻煩

3.利用反射改進

思路:工廠類通過反新的子類的路徑,並使用getInstace()方法來獲取一個類的實例。
實現
package com.learn.controller;

public class Factory {
    public static void main(String[] as) throws IllegalAccessException, InstantiationException, ClassNotFoundException {
            man m = reflectFactory.getInstance("com.learn.controller.Chinese");
            System.out.println(m.sayHello());
    }
}

interface man {
    String sayHello();
}

class Chinese implements man {

    public String sayHello() {
        return "nihao";
    }
}

class Waiguoren implements man {

    public String sayHello() {
        return "hello";
    }
}
class reflectFactory{
    public static man getInstance(String mantype) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        man man = null;
        man = (man) Class.forName(mantype).newInstance();
        return man;
    }
}

運行結構如下:

nihao

4.結合屬性文件優化

思路: 把所有類的完整路徑都寫到文件裏然後讀文件傳入工廠類中去只想say()函數
實現:

先假裝讀到了配置文件保存在了一個數組中,就是下面的mans數組

public class Factory {
    static String[] mans = new String[]{
            "com.learn.controller.Chinese",
            "com.learn.controller.Waiguoren"
    };

    public static void main(String[] as) throws IllegalAccessException, InstantiationException, ClassNotFoundException {
        man m = reflectFactory.getInstance(mans[0]);
        System.out.println(m.sayHello());
    }
}
運行結果:

你猜【尷尬臉】

5.結合註解優化

待更新

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章