Inner class - Iterator design pattern example

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wangbingfengf98/article/details/85721511

When you create an inner class, an object of that inner class contains an implicit link to the enclosing object that made it. Through this link, it can access the members of that enclosing object, without any special qualifications.

for example:

// innerclasses/Sequence.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Holds a sequence of Objects

interface Selector {
  boolean end();

  Object current();

  void next();
}

public class Sequence {
  private Object[] items;
  private int next = 0;

  public Sequence(int size) {
    items = new Object[size];
  }

  public void add(Object x) {
    if (next < items.length) items[next++] = x;
  }

  private class SequenceSelector implements Selector {
    private int i = 0;

    @Override
    public boolean end() {
      return i == items.length;
    }

    @Override
    public Object current() {
      return items[i];
    }

    @Override
    public void next() {
      if (i < items.length) i++;
    }
  }

  public Selector selector() {// returns a reference to an inner class SequenceSelector
    return new SequenceSelector();
  }

  public static void main(String[] args) {
    Sequence sequence = new Sequence(10);
    for (int i = 0; i < 10; i++) {
        sequence.add(Integer.toString(i));
    }
    Selector selector = sequence.selector();
    while (!selector.end()) {
      System.out.print(selector.current() + " ");
      selector.next();
    }
  }
}
/* Output:
0 1 2 3 4 5 6 7 8 9
*/

Above is an example of the Iterator design pattern.

Note that each of the methods—end(), current(), and next()—refers to items, a reference that isn’t part of SequenceSelector, but is instead a private field in the enclosing class. However, the inner class can access methods and fields from the enclosing class as if it owned them.

references:

1. On Java 8 - Bruce Eckel

2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/innerclasses/Sequence.java

猜你喜欢

转载自blog.csdn.net/wangbingfengf98/article/details/85721511