测试类:
package com.test;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import com.test.factory.Factory;
import com.test.productImpl.Fruit;
public class Test {
/**
* @param args
* @throws IOException
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException {
Properties pro = new Properties();
InputStream in = new FileInputStream("src/com/test/pro.properties" );
pro.load(in);
String str = pro.getProperty("apple");
Factory fac = new Factory();
Fruit f = fac.createFruit(str);
f.display();
}
}
配置文件:
apple=com.test.productImpl.Apple
orange=com.test.productImpl.Orange
banana=com.test.productImpl.Banana
产品类
package com.test.productImpl;
public class Banana implements Fruit {
public void display() {
System.out.println("Banana");
}
}
package com.test.productImpl;
public class Apple implements Fruit {
public void display() {
// TODO Auto-generated method stub
System.out.println("apple");
}
}
package com.test.productImpl;
public interface Fruit {
public abstract void display();
}
package com.test.productImpl;
public class Orange implements Fruit {
public void display() {
System.out.println("orange");
}
}
工厂类
package com.test.factory;
import com.test.productImpl.Fruit;
public class Factory {
public Fruit createFruit(String type) throws InstantiationException, IllegalAccessException, ClassNotFoundException
{
Fruit f = null;
f = (Fruit)Class.forName(type).newInstance();
return f;
}
}