1

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

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应该保留私有方法抛出的所有其他异常的堆栈跟踪。calculate()考虑到可扩展性和可维护性,您会如何推荐设计方法?

4

1 回答 1

2

I would use Composite and Command.

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

Now create an implementation for each attempt you want.

Next create a CompositeCommand -- here is an outline (you will need to fill in the blanks)

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.
    }

}

finally use it like

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

Note each command implementation is testable on its own, so this is very maintainable. If you need to add calculations, you simply define a new type of CalculateCommand, so this is extensible. It will also play well with dependency injection. Note I define a CommandContext object so different commands can take different types of stuff (put in a context).

于 2013-04-25T12:16:52.780 回答