上一次提到了工厂方法模式,经过查阅相关资料,发现可以有改进之处:
改进1.工厂方法
package com.sf.hf;
import com.sf.entity.Apple;
import com.sf.entity.Banana;
import com.sf.jk.Fruit;
public class FruitFactory {
public class FruitFactory {
public static Fruit createFruit(Class c){
//定义一个水果对象
Fruit fruit = null;
try {
fruit = (Fruit) Class.forName(c.getName()).newInstance();
} catch (Exception e) {
System.out.println("创建出错");
}
return fruit;
}
}
}
改进2.客户端调用
import com.sf.entity.Apple;
import com.sf.entity.Banana;
import com.sf.hf.FruitFactory;
import com.sf.jk.Fruit;
public class Test {
public static void main(String[] args) {
System.out.println("---------创建苹果---------");
Fruit apple = FruitFactory.createFruit(Apple.class);
apple.eat();
apple.plant();
System.out.println("---------创建香蕉--