简单工厂模式,又称静态工厂方法模式
公共接口
package com.javapatterns.simplefactory; public interface Fruit { void grow(); void harvest(); void plant(); }
具体水果
package com.javapatterns.simplefactory; public class Apple implements Fruit { public void grow() { System.out.println("Apple is growing..."); } public void harvest() { System.out.println("Apple has been harvested."); } public void plant() { System.out.println("Apple has been planted."); } public int getTreeAge(){ return treeAge; } public void setTreeAge(int treeAge){ this.treeAge = treeAge; } private int treeAge; }
package com.javapatterns.simplefactory; public class Grape implements Fruit { public void grow() { System.out.println("Grape is growing..."); } public void harvest() { System.out.println("Grape has been harvested."); } public void plant() { System.out.println("Grape has been planted."); } public boolean getSeedless() { return seedless; } public void setSeedless(boolean seedless) { this.seedless = seedless; } private boolean seedless; }
package com.javapatterns.simplefactory; public class Strawberry implements Fruit { public void grow() { System.out.println("Strawberry is growing..."); } public void harvest() { System.out.println("Strawberry has been harvested."); } public void plant() { System.out.println("Strawberry has been planted."); } }
工厂类
package com.javapatterns.simplefactory;
public class FruitGardener { public static Fruit factory(String which) throws BadFruitException { 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 BadFruitException("Bad fruit request"); } } public static void main(String []args) throws BadFruitException{ Fruit apple = factory("apple"); apple.plant(); apple.grow(); apple.harvest(); } }
异常类
package com.javapatterns.simplefactory; public class BadFruitException extends Exception { public BadFruitException(String msg) { super(msg); } }