1. 程式人生 > >23種設計模式中的叠代器模式

23種設計模式中的叠代器模式

pos over arr imp @override 一個 next() int position

叠代器模式:提供一種方法順序訪問一個聚合對象中的各個對象。

那麽如何提供一個方法順序呢?

public interface Iterator<T>{

  public boolean hasNext();

  public T next();

}

public class XXX{

  private List<XXX> list =new ArrayList<>();

  public Iterator getIterator (){

    return new XXXIterator();

  }

  class XXXIterator implements Iterator<XXX>{

    private int position;

    public XXXIterator(){
      position=0;

    }

[email protected]

    public boolean hasNext(){

       return position<list.size();

    }

[email protected]

    public XXX next(){

      XXX xxx=list.get(position++);

    }

  }

}

如果想更加了解叠代器模式,還是去看一下java內置的叠代器Iterator

23種設計模式中的叠代器模式