迭代器模式

1. 使用场景

当需要遍历某一集合(或其它对象),但又不希望遍历者知道底层集合数据结构时。

它分离了数据的存储结构和数据的遍历方式。

2. 实现举例

目标是遍历一个文本文件的每一行,用java中迭代器接口实现如下:

class FileLineIterator implements Iterable<String> {

  private BufferedReader reader;
  private String currentLine;

  public FileLineIterator(File file) throws IOException {
    super();
    this.reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
    this.currentLine = this.reader.readLine();
  }

  public void close() {
    if(this.reader != null) {
      try { this.reader.close(); } catch (IOException e) { }
    }
  }

  public Iterator<String> iterator() {
    return new Iterator<String>() {
      // 判断是否有下一行
      public boolean hasNext() {
        return currentLine != null;
      }
      // 返回下一行
      public String next() {
        try {
          String prev = currentLine;
          currentLine = reader.readLine();
          return prev;
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
      }
    };
  }
}

使用:

FileLineIterator iter = new FileLineIterator(new File("d:\\2.txt"));
for(String line : iter) {
  System.out.println(line);
}
iter.close();

results matching ""

    No results matching ""