1、策略枚举
- 使用策略枚举消除大量使用的if else
- 使用大量 if-else
public class IfService {
public String getToDo(String day) {
if ("Monday".equals(day)) {
return "今天上英语课";
} else if ("Tuesday".equals(day)) {
return "今天上语文课";
} else if ("Wednesday".equals(day)) {
return "今天上数学课";
} else if ("Thursday".equals(day)) {
return "今天上音乐课";
} else if ("sunday".equals(day)) {
return "今天上编程课";
} else {
return null;
}
}
public static void main(String[] args) {
IfService ifService = new IfService();
System.out.println(ifService.getToDo("Monday"));
}
}
结果:
- 使用枚举类进行优化大量if -else
public class CheckDay {
public String day(DayEnum dayEnum){
return dayEnum.toDo();
}
}
public enum DayEnum {
Monday{
@Override
public String toDo(){
return "周一";
}
},
Tuesday{
@Override
public String toDo(){
return "周二";
}
},
Wendsday{
@Override
public String toDo(){
return "周三";
}
},
Thursday{
@Override
public String toDo(){
return "周四";
}
},
Friday{
@Override
public String toDo(){
return "周五";
}
};
public abstract String toDo();
}
public static void main(String[] args) {
CheckDay checkDay = new CheckDay();
//可以传递参数选择哪个 枚举对象
String monday = checkDay.day(DayEnum.valueOf("Monday"));
System.out.println(monday);
}
}
- 另一种情况
public String getToDo(String day) {
//第一种情况
// if ("Monday".equals(day)) {
// return "今天上英语课";
// } else if ("Tuesday".equals(day)) {
// return "今天上语文课";
// } else if ("Wednesday".equals(day)) {
// return "今天上数学课";
// } else if ("Thursday".equals(day)) {
// return "今天上音乐课";
// } else if ("sunday".equals(day)) {
// return "今天上编程课";
// } else {
// return null;
// }
//第二种情况
if("Monday".equals(day)||"Tuesday".equals(day)||"Wednesday".equals(day)){
return "今天上英语课";
}else if("Thursday".equals(day)){
return null;
}
return null;
}
public class CheckDay {
public String dayNew(DayEnumNew dayEnumNew) {
return dayEnumNew.toDo();
}
}
public enum DayEnumNew {
Monday(Type.ENGLISH, "星期一"),
Tuesday(Type.ENGLISH, "星期二"),
Wednesday(Type.ENGLISH, "星期三"),
Thursday(Type.CHINESE, "星期四");
private final Type type;
private final String day;
DayEnumNew(Type type, String day) {
this.type = type;
this.day = day;
}
String toDo(){
return type.toDo();
}
/**
* 内部策略枚举
*/
private enum Type {
ENGLISH {
@Override
public String toDo() {
return "今天上英语课";
}
},
CHINESE {
@Override
public String toDo() {
return "今天上语文课";
}
};
public abstract String toDo();
}
}
public static void main(String[] args) {
CheckDay checkDay = new CheckDay();
//可以传递参数选择哪个 枚举对象
// String monday = checkDay.day(DayEnum.valueOf("Monday"));
// System.out.println(monday);
String monday = checkDay.dayNew(DayEnumNew.valueOf("Monday"));
String thursday = checkDay.dayNew(DayEnumNew.valueOf("Thursday"));
String thursday1 = checkDay.dayNew(DayEnumNew.valueOf("Wednesday"));
System.out.println(monday);
System.out.println(thursday);
System.out.println(thursday1);
}
结果: