public class Banana implements Fruit{
//获得香蕉
public void get(){
System.out.println("采集香蕉");
}
}
public class Apple implements Fruit{
/*
* 获得苹果
*/
public void get(){
System.out.println("采集苹果");
}
}
public class FruitFactory {
// /*
// * 获得Apple类的实例
// */
// public static Fruit getApple() {
// return new Apple();
// }
//
// /*
// * 获得Banana类实例
// */
// public static Fruit getBanana() {
// return new Banana();
// }
/*
* get方法,获得所有产品对象
*/
public static Fruit getFruit(String type) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
// if(type.equalsIgnoreCase("apple")) {
// return Apple.class.newInstance();
//
// } else if(type.equalsIgnoreCase("banana")) {
// return Banana.class.newInstance();
// } else {
// System.out.println("找不到相应的实例化类");
// return null;
// }
Class fruit = Class.forName(type);
return (Fruit) fruit.newInstance();
}
}
public class MainClass {
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
// //实例化一个Apple
// Apple apple = new Apple();
// //实例化一个Banana
// Banana banana = new Banana();
//
// apple.get();
// banana.get();
// //实例化一个Apple,用到了多态
// Fruit apple = new Apple();
// Fruit banana = new Banana();
// apple.get();
// banana.get();
// //实例化一个Apple
// Fruit apple = FruitFactory.getApple();
// Fruit banana = FruitFactory.getBanana();
// apple.get();
// banana.get();
Fruit apple = FruitFactory.getFruit("Apple");
Fruit banana = FruitFactory.getFruit("Banana");
apple.get();
banana.get();
}
}
|
|