简单工厂模式: 传递构造参数,用一个Static的工厂方法根据参数产生具体的实例,这个扩展麻烦,不符合开闭原则 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"); } }
传递构造参数,用一个Static的工厂方法根据参数产生具体的实例,这个扩展麻烦,不符合开闭原则
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");
}
}