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)。

猜你喜欢

转载自blog.csdn.net/baiyan3212/article/details/87876271