您好我的代码将遵循序列过程。
每个可能的部分都有失败的情况。
我想知道这个过程被哪个部分阻止了。 因此,有一种状态可以知道该方法在哪种方法上失败。
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
我的问题是,是否有一种设计模式可以让我的代码更美观。
答案 0 :(得分:1)
对于错误处理,请使用例外:
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();
}
}
答案 1 :(得分:0)
州,https://en.m.wikipedia.org/wiki/State_pattern,可能就是你在这里寻找的东西。
修改的
您的特定问题的一个解决方案可能是将方法实现为实现您添加到集合类的接口的lambda表达式,然后遍历集合并执行每个集合直到所有已执行或者返回失败状态