公共接口Fruit
package factory;
public interface Fruit {
void eat();
}
实现类Apple
package factory;
public class Apple implements Fruit {
@Override
public void eat() {
System.out.println("apple");
}
}
实现类Orange
package factory;
public class Orange implements Fruit {
@Override
public void eat() {
System.out.println("orange");
}
}
工厂类FruitFactory
package factory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class FruitFactory {
public static Fruit getInstance(String fruitName){
Fruit fruit=null;
if ("apple".equals(fruitName)) {
fruit=new Apple();
}else if ("orange".equals(fruitName)) {
fruit=new Orange();
}
return fruit;
}
//使用反射的工厂模式
public static Fruit getInstanceByReflect(String className){
Fruit fruit=null;
try {
fruit = (Fruit) Class.forName(className).newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return fruit;
}
public static void main(String[] args) {
Fruit fruit = FruitFactory.getInstance("apple");
Fruit orange = FruitFactory.getInstanceByReflect("factory.Orange");
fruit.eat();
orange.eat();
Fruit fruit2=null;
try {
fruit2 = FruitFactory.getInstanceByReflect(init().getProperty("apple"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fruit2.eat();
}
//使用配置文件加反射的工厂模式
public static Properties init() throws FileNotFoundException, IOException{
File file=new File("fruit.properties");
Properties properties=new Properties();
if (file.exists()) {
properties.load(new FileInputStream(file));
}else{
properties.setProperty("apple", "factory.Apple");
properties.setProperty("orange", "factory.Orange");
properties.store(new FileOutputStream(file), "Fruit Class");
}
return properties;
}
}
工厂类中有两种方法获取实例第一种是传统的方式很显然不够灵活每当我们增加一个实现类就会修改对应的工厂类,
而使用反射加配置文件的方式就可以灵活创建多个实例。
参考博客http://www.cnblogs.com/rollenholt/archive/2011/09/02/2163758.html#undefined