我会首先将 C 代码重构为不那么重复的代码:
enum { STEP1, STEP2, STEP3, /*...*/ };
typedef int ThingToTry();
ThingToTry *things_to_try[MAX_STEP] = {
try_something,
try_next_thing,
/*...*/
};
int next_step (int (*thing_to_try)(), int true_step, int false_step) {
for (int i = 0; i < MAX_ATTEMPT; i++) {
if (thing_to_try()) return true_step;
}
return false_step;
}
/*...*/
step = STEP1;
while (step != MAX_STEP) {
if (step == STEP1) {
/*...initialization */
}
step = next_step(things_to_try[step], step+1, STEP1);
}
Java中对应的代码:
enum StepEnum { STEP1, STEP2, STEP3, //...
}
interface ThingToTry {
bool do_it ();
}
class TrySomething extends ThingToTry //...
class TryNextThing extends ThingToTry //...
StepEnum next_step (ThingToTry thing_to_try,
StepEnum true_step, StepEnum false_step) {
for (int i = 0; i < MAX_ATTEMPTS; ++i) {
if (thing_to_try.do_it()) return true_step;
}
return false_step;
}
//...
ThingToTry[MAX_STEP] things_to_try = {
new TrySomething,
new TryNextThing,
//...
};
while (step != MAX_STEP) {
if (step == STEP1) {
//...initialization
}
StepEnum true_step = StepEnum.values()[step.ordinal()+1];
step = next_step(things_to_try[step.ordinal()], true_step, STEP1);
}