java工厂模式实例化class

import java.io.*;
import java.util.*;

interface fruit {
    public abstract 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 FileNotFoundException, IOException {
        Properties pro = new Properties();
        File f = new File("fruit.properties");
        if (f.exists()) {
            pro.load(new FileInputStream(f));
        } else {
            pro.setProperty("apple", "Apple");
            pro.setProperty("orange", "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 FileNotFoundException,
            IOException {
        Properties pro = init.getPro();
        fruit f = Factory.getInstance(pro.getProperty("apple"));
        if (f != null) {
            f.eat();
        }
    }
}

如果之前没有配置文件,就会生成一个配置文件如下:

#FRUIT CLASS
#Sun Sep 08 11:32:46 CST 2013
apple=Apple
orange=Orange

 

posted @ 2013-09-08 11:37  yanghuahui  阅读(1451)  评论(0编辑  收藏  举报