当程程序中出现if else 时代码看起来非常的乱,这是可以通过其他的实现方式来代替if else 语句。
public static void conditionMethod(Integer type){
if (type==1)
statementOne(type);
else if(type==2)
statementSecond(type);
else
statementOther(type);
}
private static void statementOther(Integer type) {
System.out.println(type);
}
private static void statementSecond(Integer type) {
System.out.println(type);
}
private static void statementOne(Integer type) {
System.out.println(type);
}
方法一:使用switch语句。
public static void swithMethod(Integer type){
switch (type){
case 1 :statementOne(type); break;
case 2: statementSecond(type);break;
default:statementOther(type);break;
}
}
方法二:使用策略模式
public static void stategyMethod(Integer type){
Strategy strategy= stategys.get(type);
strategy.apply(type);
}
//定义策略接口
public interface Strategy {
void apply(Integer type);
}
//不同分支的实现
public class StrategyOne implements Strategy {
@Override
public void apply(Integer type) {
System.out.println(type);
}
}
...
方法三:枚举方式
public enum EnumType {
ONE(1){
@Override
void statement() {
System.out.println(type);
}
},
SECONDE(2){
@Override
void statement() {
System.out.println(type);
}
},
OHTER(4){
@Override
void statement() {
System.out.println(type);
}
};
public int type;
abstract void statement();
EnumType (int type){
this.type =type;
}
}
public static void enumMethod(String type){
EnumType et= EnumType.valueOf(type);
et.statement();
}
其他方法,java8 新特新Optional ,适用于两个分支的情况
public static void optionalMethod(String type){
Optional<String> types =Optional.ofNullable(type);
types.map("action1").orElse("action2");
}
分享到: