您好,我的代码将遵循顺序过程。
每个可能的部分都会出现失败情况。
我想知道进程被哪一部分阻止了。 所以有一个状态可以知道进程在哪个方法上失败了。
public class MethodSequenceDesign {
public static final int STATE_WAIT = 0;
public static final int STATE_A_RUNNING = 1;
public static final int STATE_A_FAIL = 2;
public static final int STATE_B_RUNNING = 3;
public static final int STATE_B_FAIL = 4;
public static final int STATE_C_RUNNING = 5;
public static final int STATE_C_FAIL = 6;
public static final int STATE_END = 7;
static int status = STATE_WAIT;
public void start() {
if (!methodA()) {
status = STATE_A_FAIL;
return;
}
if (!methodB()) {
status = STATE_B_FAIL;
return;
}
if (!methodC()) {
status = STATE_C_FAIL;
return;
}
status = STATE_END;
}
public boolean methodA() {
status = STATE_A_RUNNING;
String str = "do some operation in method A";
System.out.println(str);
return randomBoolean();
}
public boolean methodB() {
status = STATE_B_RUNNING;
String str = "do some operation in method B";
System.out.println(str);
return randomBoolean();
}
public boolean methodC() {
status = STATE_C_RUNNING;
String str = "do some operation in method C";
System.out.println(str);
return randomBoolean();
}
public static void main(String[] args) {
MethodSequenceDesign method = new MethodSequenceDesign();
method.start();
System.out.println("Final state = " + status);
}
public boolean randomBoolean() {
Random random = new Random();
return random.nextBoolean();
}
}
我这里有我的示例代码: https://ideone.com/4Rw0Zs
我的问题是,是否有一种设计模式可以美化我的代码。
最佳答案
对于错误处理,请使用异常:
public class MethodSequenceDesign {
public void start() {
if (!methodA()) {
throw new RuntimeException("methodA failed");
}
if (!methodB()) {
throw new RuntimeException("methodB failed");
}
if (!methodC()) {
throw new RuntimeException("methodC failed");
}
}
public boolean methodA() {
String str = "do some operation in method A";
System.out.println(str);
return randomBoolean();
}
public boolean methodB() {
String str = "do some operation in method B";
System.out.println(str);
return randomBoolean();
}
public boolean methodC() {
String str = "do some operation in method C";
System.out.println(str);
return randomBoolean();
}
public static void main(String[] args) {
MethodSequenceDesign method = new MethodSequenceDesign();
try{
method.start();
} catch (Exception e) {
e.printStacktrace();
}
}
public boolean randomBoolean() {
Random random = new Random();
return random.nextBoolean();
}
}
关于Java方法流程状态设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49062369/