考虑一下
execute around idiom.
另一个选项(实际上并非完全不同,它只是将它们分离出来)是在一个单独的线程中完成每个任务.
编辑:
这是我的想法:
public interface LoadableDriver {
public String getName();
public void loadDriver() throws DriverException;
public void onError(Throwable e);
}
public class DriverLoader {
private Map errors = new HashMap();
public void load(LoadableDriver driver) {
try {
driver.loadDriver();
} catch (DriverException e) {
errors.put(driver.getName(), e);
driver.onError(e);
}
}
public Map getErrors() { return errors; }
}
public class Main {
public void loadDrivers() {
DriverLoader loader = new DriverLoader();
loader.loadDriver(new LoadableDriver(){
public String getName() { return "SoundDriver"; }
public void loadDriver() { loadSoundDriver(); }
public void onError(Throwable e) { doSomethingA(); }
});
//etc. Or in the alternative make a real class that implements the interface for each driver.
Map errors = loader.getErrors();
//react to any specific drivers that were not loaded and try again.
}
}
编辑:如果您将驱动程序实现为类(这就是Java OO范例在此处预期的恕我直言),这就是干净的Java版本最终会是什么样子. Main.loadDrivers()方法将改变如下:
public void loadDrivers(LoadableDriver... drivers) {
DriverLoader loader = ...
for(LoadableDriver driver : drivers) {
loader.load(driver);
}
//retry code if you want.
Set failures = loader.getErrors();
if(failures.size() > 0 && tries++ > MAX_TRIES) {
//log retrying and then:
loadDrivers(drivers.toArray(new LoadableDriver[0]));
}
}
当然我不再使用地图,因为对象是自给自足的(你可以去除getName()方法,但可能应该覆盖toString()),所以错误只是在一组中返回重试.如果每个驱动程序都有责任知道它应该重试的频率,那么您可以使重试代码更简单.
Java看起来不如一个做得好的C模板,但这是Java语言设计的选择 – 更喜欢简单而不是复杂的语言功能,如果不能正确完成,可能会使代码难以维护.