private List<MealsVO> changeMeals(String mealPlan){ List<MealsVO> meals = Lists.newArrayList(); MealsVO vo = new MealsVO(); MealsVO vo1 = new MealsVO(); MealsVO vo2 = new MealsVO(); if(mealPlan.equals(MealCode.RO)){ vo.setNum(0); vo.setType(4); meals.add(vo); return meals; }else if(mealPlan.equals(MealCode.BB)){ vo.setNum(1); vo.setType(1); meals.add(vo); return meals; }else if(mealPlan.equals(MealCode.HB)){ vo.setNum(1); vo.setType(1); vo1.setNum(1); vo1.setType(3); meals.add(vo); meals.add(vo1); return meals; }else if(mealPlan.equals(MealCode.FB)){ vo.setNum(1); vo.setType(1); vo1.setNum(1); vo1.setType(3); vo2.setNum(1); vo2.setType(2); meals.add(vo); meals.add(vo2); meals.add(vo1); return meals; } return null; }代码优化
时间: 2024-02-14 15:16:20 浏览: 141
可以通过使用switch语句来替换if-else语句,同时可以使用Map来存储不同餐饮方案对应的餐饮信息,以避免代码中的重复代码。以下是代码优化的示例:
```
private static final Map<String, List<MealsVO>> MEAL_PLAN_MAP = new HashMap<>();
static {
MEAL_PLAN_MAP.put(MealCode.RO, Collections.singletonList(new MealsVO(4, 0)));
MEAL_PLAN_MAP.put(MealCode.BB, Collections.singletonList(new MealsVO(1, 1)));
MEAL_PLAN_MAP.put(MealCode.HB, Arrays.asList(new MealsVO(1, 1), new MealsVO(3, 1)));
MEAL_PLAN_MAP.put(MealCode.FB, Arrays.asList(new MealsVO(1, 1), new MealsVO(2, 1), new MealsVO(3, 1)));
}
private List<MealsVO> changeMeals(String mealPlan) {
return MEAL_PLAN_MAP.getOrDefault(mealPlan, Collections.emptyList());
}
```
在上述优化后的代码中,我们使用了静态初始化块来初始化餐饮方案和对应的餐饮信息的Map,然后使用switch语句的替换,最后通过Map.getOrDefault()方法来获取对应餐饮方案的餐饮信息。
阅读全文