Java design patterns described in (13): iterator pattern

This article Source: GitHub · Click here || GitEE · Click here

First, the iterator pattern

1, the basic concept

Iterator pattern known as cursor mode is the behavior of the object. Iterator pattern element may be sequentially accessed in a clustered appearance without having to expose the interior of the aggregate.

2, illustrates a pattern

3, the core role

  • Iterator: Iterator role

This abstract definition of the role of the required traverse the interface elements.

  • ConcreteIterator: concrete iterator role

This role implements Iterator interface, and keep the cursor position iterative process.

  • Aggregate: aggregate role

This role is given to create abstract iterator (Iterator) object's interface.

  • ConcreteAggregate: gather specific role

Polymerization holds a collection of objects, there is provided a method returns an iterator can traverse the set correctly.

  • Client: Client Role

To gather and hold iterator object reference, call the interface iterator iterator object.

4, the source case

public class C02_Iterator {
    public static void main(String[] args) {
        Object[] objArray = {"one","two","three","four","five"};
        Aggregate aggregate = new ConcreteAggregate(objArray);
        Iterator iterator = aggregate.createIterator();
        while (!iterator.isEnd()){
            System.out.println(iterator.currentItem());
            iterator.next();
        }
    }
}
interface Iterator {
    void first();
    void next();
    boolean isEnd();
    Object currentItem();
}
class ConcreteIterator implements Iterator{
    //持有被迭代的聚合对象
    private ConcreteAggregate agg;
    //记录当前迭代索引位置
    private int index = 0;
    //设置当前聚集对象的大小
    private int size = 0;
    public ConcreteIterator (ConcreteAggregate agg){
        this.agg = agg;
        this.size = agg.getSize();
        index = 0;
    }
    @Override
    public void first() {
        index = 0;
    }
    @Override
    public void next() {
        if (index<size){
            index++;
        }
    }
    @Override
    public boolean isEnd() {
        return (index>=size);
    }
    @Override
    public Object currentItem() {
        return agg.getElement(index);
    }
}
abstract class Aggregate {
    // 创建相应迭代器对象的接口
    public abstract Iterator createIterator();
}
class ConcreteAggregate extends Aggregate{
    private Object[] objArray = null;
    public ConcreteAggregate (Object[] objArray){
        this.objArray = objArray;
    }
    @Override
    public Iterator createIterator() {
        return new ConcreteIterator(this);
    }
    public Object getElement (int index){
        if (index<objArray.length){
            return objArray[index];
        } else {
            return null;
        }
    }
    public int getSize (){
        return objArray.length;
    }
}

Two, JDK collection application

1, a simple case

public class C02_ArrayList {
    public static void main(String[] args) {
        List<String> stringList = new ArrayList<>() ;
        stringList.add("One") ;
        stringList.add("Two") ;
        stringList.add("Three") ;
        java.util.Iterator<String> itr = stringList.iterator() ;
        while (itr.hasNext()){
            System.out.println(itr.next());
        }
    }
}

2, Iterator source

It provides a number of iterative method of collection.

public interface Iterator<E> {
    boolean hasNext();
    E next();
    default void remove() {
        throw new UnsupportedOperationException("remove");
    }
    default void forEachRemaining(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        while (hasNext())
            action.accept(next());
    }
}

3, ArrayList source

  • Achieve an aggregate interface List
ArrayList<E> extends AbstractList<E> implements List<E>
  • Internal iterator interface
private class Itr implements Iterator<E> {
    int cursor;
    int lastRet = -1;
    int expectedModCount = modCount;
    Itr() {}
    public boolean hasNext() {}
    public E next() {}
    public void remove() {}
    public void forEachRemaining(Consumer<? super E> consumer) {}
    final void checkForComodification() {}
}
  • Returns an iterator
public Iterator<E> iterator() {
    return new Itr();
}

Third, the iterator summary

1, application scenarios

Iterator pattern is a set of bindings, just use a collection, you need to iterate through this collection the same time, in order to traverse the data collection, java container object in the Collection, List, Set, Map has its own iterator. Container object in the very core programming language, so in the realization of the basic container iterators are matched to meet the needs of development, so the scene is relatively small custom practice iterator.

2, summarizes the advantages

A simplified set of traversal, each aggregated object can have one or more iterator object, the state of each iteration iterator may be independent of each other. In the traversal algorithm is encapsulated inside the iterator role, so iterative algorithm may be independent of the changing role of aggregation.

Fourth, the source address

GitHub·地址
https://github.com/cicadasmile/model-arithmetic-parent
GitEE·地址
https://gitee.com/cicadasmile/model-arithmetic-parent

Guess you like

Origin www.cnblogs.com/cicada-smile/p/11570299.html