switch 选择因子只能为 整数!!
今天练习工厂模式,根据传入的字符串连选择生成的对象,看教材上写的是用if条件选择语句来进行的,自己想着用其他的方法来写一下,就选择 用switch语句,由于选择因子是字符串,编译器老报错,于是查了一下资料,表面switch的选择因子只能是整数 。
?
package interfaces.fruit;public class FruitGardener {public static Fruit Factory(String which) throws BadFruitException{/*switch(which){default:throw new BadFruitException("bad fruit request");case(which.equalsIgnoreCase("Apple")):return new Apple();case(which.equalsIgnoreCase("Grape")):return new Grape();case(which.equalsIgnoreCase("StrawBerry")):return new StrawBerry();}*/if(which.equalsIgnoreCase("Apple")){return new Apple();}else if(which.equalsIgnoreCase("Grape")){return new Grape();}else if(which.equalsIgnoreCase("StrawBerry")){return new StrawBerry();}else{throw new BadFruitException("bad fruit request");}}public static void main(String[] args) {}}
?