SpringIoc 和 工廠模式(反射實現)

package org;

interface Fruit {
    public void eat();
}

class Apple implements Fruit {
    public void eat() {
        System.out.println("吃蘋果。");
    }
}

class Orange implements Fruit {
    public void eat() {
        System.out.println("吃橘子");
    }
}

class Factory { // 工廠類
    public static Fruit getInstance(String className) {
        Fruit f = null;
        if (className.equals("apple")) {
            f = new Apple();
        }
        if (className.endsWith("orange")) {
            f = new Orange();
        }
        return f;
    }
}

public class FactoryDemo {
    public static void main(String args[]) {
        Fruit f = Factory.getInstance("apple");
        f.eat();
    }
}

問題:若增加新水果,如香蕉,則工廠類也要修改.

解決:java的反射機制.

二、修改“工廠類”:

//工廠類(修改)
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;
    }
}

問題:創建實例時,需要提供“完整的類名”

public class FactoryDemo2 {
    public static void main(String args[]) {
        Fruit f = Factory.getInstance("org.Orange");
        f.eat();
    }
}

解決:增加“配置文件”優化.

三、增加“配置文件”:

class PropertiesOperate{  
    private Properties pro=null;  
    private File file=new File("d:"+File.separator+"fruit.properties");  
      
    public PropertiesOperate(){  
        pro=new Properties();  
        if(file.exists()){  
            try {  
                pro.loadFromXML(new FileInputStream(file));  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }else{  
            this.save();  
        }  
    }  
    private void save(){  
        pro.setProperty("apple","org.Apple");  
        pro.setProperty("orange", "org.Orange");  
        try {  
            pro.storeToXML(new FileOutputStream(this.file),"Fruit");  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
    public Properties getProperties(){  
        return pro;  
    }  
}
public class FactoryDemo3 {
    public static void main(String args[]) {
        Properties pro=new PropertiesOperate().getProperties();  
        Fruit f= Factory.getInstance(pro.getProperty("orange")); 
        f.eat();
    }
}

通過配置文件,可以控制程序的執行,現在看起來有點像spring的ioc了。

 

該程序使用了工廠模式,把所有的類放在一個Factory裏面,而爲了動態的管理這些類(即使增加了新的Fruit類,這個工廠也不用變化),就用了java的反射機制。

另外,通過配置文件,使得一長串完整的類名稱(如org.Apple)可用任意簡短的名稱來代替(如apple)。

 

 

 

 

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