我正在编写一个协议类,其中包含很多if / elses ......这是类:
public class Protocol {
Scanner scan = new Scanner(System.in);
private static final int WAITING = 0;
private static final int SENTREQUEST = 1;
private static final int SENTITEMS = 2;
private static final int ANOTHER = 3;
private static final int CHOICE = 4;
private int choice;
private int state = WAITING;
public String processInput(String theInput) {
String theOutput = null;
if (state == WAITING) {
theOutput = "Do you accept the terms of agreement? Y/N?";
state = SENTREQUEST;
} else if (state == SENTREQUEST) {
if (theInput.equalsIgnoreCase("y")) {
theOutput = ": 1. program file 2. pictures 3. documentation";
state = CHOICE;
} else {
theOutput = "Invalid Input!";
state = SENTITEMS;
}
}
else if (state == CHOICE) {
choice = scan.nextInt();
switch(choice) {
case 1: theOutput = "show something";
break;
case 2: theOutput = "show something";
break;
case 3: theOutput = "show something";
break;
}
}
else if (state == SENTITEMS) {
theOutput = "Want another? (y/n)";
state = ANOTHER;
} else if (state == ANOTHER) {
theOutput = "Do you accept the terms of agreement? Y/N?";
if (theInput.equalsIgnoreCase("y")) {
theOutput ="test";
state = SENTREQUEST;
} else {
theOutput = "Bye.";
state = WAITING;
}
}
return theOutput;
}
}
它没有进入切换案例,我确定这是一个正确地打破if / elses子句但我找不到问题的问题。
答案 0 :(得分:1)
为了解决类似的问题,我将strategy pattern实现为枚举。对于每个策略,您为枚举创建一个新值,在枚举方法中包含代码:
public enum Strategy {
FIRST_STRATEGY {
public String process(String input) {
// Implementation for first strategy
return null;
}
},
SECOND_STRATEGY {
public String process(String input) {
// Implementation for second strategy
return null;
}
};
public abstract String process(String input);
}
您可以根据您拥有的枚举值应用所选策略,实际上删除了if / else语句链:
Strategy chosenStrategy = Strategy.FIRST_STRATEGY;
String output = chosenStrategy.process(input);
这是我为我的一个问题申请的解决方案,也许它不是最优的,也不是面向对象的。您必须为您的问题选择正确的解决方案,但我希望我的经验可以提供帮助。
答案 1 :(得分:0)
使用这样的状态模式:
public class Protocol {
Scanner scan = new Scanner(System.in);
private abstract class State { abstract String doit(String theInput); }
private final class WAITING extends State {
String doit(String theInput) {
state = SENTREQUEST;
return "Do you accept the terms of agreement? Y/N?";
}
}
private final class SENTREQUEST extends State {
String doIt(String theInput) {
if (theInput.equalsIgnoreCase("y")) {
state = CHOICE;
return ": 1. program file 2. pictures 3. documentation";
} else {
state = SENTITEMS;
return "Invalid Input!";
}
}
}
//TODO refactoring to State classes for all
// private static final int SENTITEMS = 2;
// private static final int ANOTHER = 3;
// private static final int CHOICE = 4;*/
private int choice;
private State state = WAITING;
public String processInput(String theInput) {
return state.doIt(theInput);
}
}