jeudi 13 octobre 2016

Iterator Pattern implemented inside of Composite Pattern

I am working on a project for Design Patterns, and I am trying to implement an iterator within my composite base class. The problem though is that I am getting errors from the compiler not knowing what the symbol T is. I am using generics in the interface for my iterator.

Here is my code for the Iterator interface:

interface Iter<T> {
  public void first();
  public void next();
  public boolean isDone();
  public T currentItem();
}

And here is my code for the Composite base class:

abstract class Composite extends Component {

  public Iter<T> makeIter() {
    return new Iter<T>() {
      private Component component = this;
      private int _count = 0;

      public void first() {
        // position the iterator to the first element
        _count = 0;
      }

      public void next() {
        // advances the current element
        _count += 1;
      }

      public boolean isDone() {
        // returns true if iterator has cycled all the way through
        return _count >= component.getSize();
      }

      public Component currentItem() {
        // returns current item iterator is positioned on
        return component.getChild(_count);
      }
    };
  }

  //abstract primitive methods to implement
  @Override
  public abstract Component getChild(int number);
  @Override
  protected abstract void doAdd(Component part);
  @Override
  protected abstract void doRemove(Component part);


}

Here is the error message that I am getting:

Component.java:38: error: cannot find symbol
  abstract public Iter<T> makeIter();
                   ^
  symbol:   class T
  location: class Component
Composite.java:5: error: cannot find symbol
  public Iter<T> makeIter() {

I am not a 100% sure I am implementing this in the right way, but I know that for the project we need to implement the iterator within the composite base class. Any help is much appreciated.

Aucun commentaire:

Enregistrer un commentaire