有人使用这样的方式来实现责任链

2017-11-28  本文已影响37人  brzhang
@Override
  public void dump(DumperContext dumpContext) throws DumpException {
    PrintStream writer = dumpContext.getStdout();
    Iterator<String> argsIter = dumpContext.getArgsAsList().iterator();

    String command = ArgsHelper.nextOptionalArg(argsIter, null);

    if (CMD_LIST.equalsIgnoreCase(command)) {
      doList(writer);
    } else if (CMD_DELETE.equalsIgnoreCase(command)) {
      doRemove(writer, argsIter);
    } else if (CMD_CLEAR.equalsIgnoreCase(command)) {
      doClear(writer);
    } else if (CMD_REFRESH.equalsIgnoreCase(command)) {
      doRefresh(writer);
    } else {
      usage(writer);
      if (command != null) {
        throw new DumpUsageException("Unknown command: " + command);
      }
    }
  }

第一个参数作为命令已经被消耗掉了,后面的参数属于后面的部分取过来使用

public class ArgsHelper {
  public static String nextOptionalArg(Iterator<String> argsIter, String defaultValue) {
    return argsIter.hasNext() ? argsIter.next() : defaultValue;
  }

  public static String nextArg(Iterator<String> argsIter, String errorIfMissing)
      throws DumpUsageException {
    if (!argsIter.hasNext()) {
      throw new DumpUsageException(errorIfMissing);
    }
    return argsIter.next();
  }

  public static String[] drainToArray(Iterator<String> argsIter) {
    List<String> args = new ArrayList<>();
    while (argsIter.hasNext()) {
      args.add(argsIter.next());
    }
    return args.toArray(new String[args.size()]);
  }
}
上一篇下一篇

猜你喜欢

热点阅读