gpt4 book ai didi

java - 错误/异常累积设计模式

转载 作者:行者123 更新时间:2023-11-30 04:24:48 25 4
gpt4 key购买 nike

方法返回一些结果,进行多次“尝试”来构建它。第一次成功的尝试应该返回。如果它们都没有成功,则应抛出异常:

class Calculator {
public String calculate() throws Exception {
// how do design it?
}
private String attempt1() throws Exception {
// try to calculate and throw if fails
}
private String attempt2() throws Exception {
// try to calculate and throw if fails
}
private String attempt3() throws Exception {
// try to calculate and throw if fails
}
}

值得一提的是,calculate 引发的异常应该保留私有(private)方法引发的所有其他异常的堆栈跟踪。您建议如何设计 calculate() 方法,同时考虑到可扩展性和可维护性?

最佳答案

我会使用复合和命令。

interface CalculateCommand {
public void calculate(CalculateContext context);
}

现在为您想要的每次尝试创建一个实现。

接下来创建一个 CompositeCommand - 这是一个大纲(您需要填写空白)

public class CompositeCalculateCommand implements CalculateCommand {

CompositeCalculateCommand(List<CompositeCommand> commands) {
this.commands = commands; // define this as a field
}

public void calculate(CommandContext context) {
for (CalculateCommand command : commands) {
try {
command.calculate(context);
} catch(RuntimeException e) {
this.exceptions.add(e) // initialize a list to hold exceptions
}
if (context.hasResult) return; // break
}
// throw here. You didn't success since you never saw a success in your context. You have a list of all exceptions.
}

}

最后像这样使用它

CalculateCommand allCommands = new CompositeCalculateCommand(someListOfCommands);
allCommands.calculate(someContextThatYouDefine);
// results now on context.

请注意,每个命令实现都可以自行测试,因此非常易于维护。如果您需要添加计算,您只需定义一个新类型的CalculateCommand,因此这是可扩展的。它还可以很好地与依赖注入(inject)配合使用。请注意,我定义了一个 CommandContext 对象,以便不同的命令可以采用不同类型的内容(放入上下文中)。

关于java - 错误/异常累积设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16214367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com