图5. 工厂方法模式在小花果园系统中的实现 抽象工厂类 Gardener 是工厂方法模式的核心,但是它并不把握水果类或蔬菜类的生杀大权。相反地,这项权力被交给子类,即 VeggieGardener 及 FruitGardener。 package com.javapatterns.factorymethod; abstract public class Gardener { public abstract PlantIF factory(String which) throws BadFruitException; } 代码清单1. 父类 Gardener。 package com.javapatterns.factorymethod;
public class VeggieGardener extends Gardener { public PlantIF factory(String which) throws BadPlantException { if (which.equalsIgnoreCase("tomato")) { return new Tomato(); } else if (which.equalsIgnoreCase("potato")) { return new Potato(); } else if (which.equalsIgnoreCase("broccoli")) { return new Broccoli(); } else { throw new BadPlantException("Bad veggie request"); } }
} 代码清单2. 子类 VeggieGardener。
package com.javapatterns.factorymethod;
public class FruitGardener extends Gardener { public PlantIF factory(String which) { if (which.equalsIgnoreCase("apple")) { return new Apple(); } else if (which.equalsIgnoreCase("strawberry")) { return new Strawberry(); } else if (which.equalsIgnoreCase("grape")) { return new Grape(); } else { throw new BadPlantException("Bad fruit request"); } } } 代码清单3. 子类 FruitGardener。 package com.javapatterns.factorymethod;
public class Broccoli implements VeggieIF, PlantIF { public void grow() { log("Broccoli is growing..."); }
public void harvest() { log("Broccoli has been harvested."); } public void plant() { log("Broccoli has been planted."); } private static void log(String msg) { System.out.println(msg); } public void pesticideDust(){ } } 代码清单4. 蔬菜类 Broccoli。其它的蔬菜类与 Broccoli 相似,因此不再赘述。 package com.javapatterns.factorymethod; public class Apple implements FruitIF, PlantIF { public void grow() { log("Apple is growing..."); } public void harvest() { log("Apple has been harvested."); } public void plant() { log("Apple has been planted."); }